# Pinia 状态管理
uni-app x 蒸汽(vapor)模式下可直接使用
pinia官方库,无需 npm 安装依赖。通过defineStore定义全局响应式 store,配合storeToRefs在页面中解构使用,数据修改后界面自动更新。
安装与挂载
从 HBuilderX 5.25 起,uni-app x 项目的 pinia 升级到了 3.0.4 版本,内置支持,无需在项目根目录额外安装。
在 main.uts 中引入并挂载 Pinia:
ts
import App from './App.uvue'
import { createSSRApp } from 'vue'
import { createPinia } from 'pinia'
export function createApp() {
const app = createSSRApp(App)
app.use(createPinia())
return {
app
}
}定义一个 Store
在 store/counter.uts 中定义 store,例如:
ts
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const name = ref('Pinia')
const count = ref(0)
const doubleCount = computed(() : number => {
return count.value * 2
})
const countText = computed(() : string => {
return `${name.value}: ${count.value}`
})
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
const rename = () => {
name.value = name.value == 'Pinia' ? 'Pinia Store' : 'Pinia'
}
const reset = () => {
name.value = 'Pinia'
count.value = 0
}
return {
name,
count,
doubleCount,
countText,
increment,
decrement,
rename,
reset
}
})页面中使用 Store
通过 storeToRefs 解构出响应式数据,通过 counterStore.xxx 调用 store 内的方法:
html
<template>
<view class="p-15">
<tui-theme-switch></tui-theme-switch>
<t-card class="mb-15"
title="Pinia 状态管理"
subTitle="蒸汽模式下可直接使用 pinia 官方库,通过 defineStore 定义 store,配合 storeToRefs 在页面中解构使用"></t-card>
<t-section class="r-10 mb-15"
title="Store 数据展示"
subTitle="数据由 store/counter.uts 全局响应"></t-section>
<t-col class="r-10 mb-15 p-10">
<t-text class="mb-5">name:{{ name }}</t-text>
<t-text class="mb-5">count:{{ count }}</t-text>
<t-text class="mb-5">double count:{{ doubleCount }}</t-text>
<t-text class="mb-5">count text:{{ countText }}</t-text>
</t-col>
<t-col class="r-10 p-10">
<t-button type="primary"
effect="light"
class="mb-15"
@click="increment">increment 增加</t-button>
<t-button type="warning"
effect="light"
class="mb-15"
@click="decrement">decrement 减少</t-button>
<t-button type="info"
effect="light"
class="mb-15"
@click="rename">rename 重命名</t-button>
<t-button type="error"
effect="light"
@click="reset">reset 重置</t-button>
</t-col>
</view>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/store/counter.uts'
const counterStore = useCounterStore()
const { name, count, doubleCount, countText } = storeToRefs(counterStore)
const increment = () => {
counterStore.increment()
}
const decrement = () => {
counterStore.decrement()
}
const rename = () => {
counterStore.rename()
}
const reset = () => {
counterStore.reset()
}
</script>注意事项
- 蒸汽(vapor)模式、鸿蒙和 iOS VDOM 模式、Web 平台、小程序平台可以直接使用
pinia官方库;Android VDOM 模式需使用三方插件 Pinia by uts。 - 如果需要持久化存储,可结合 TuiStore 使用。
- 如果数据不需要绑定界面(非响应式),可直接使用
globalData存储。