Skip to content

pinia 状态管理 ​

17:43

跨页面共享状态用 pinia。uni-app x 内置 pinia 3.0.4,项目无需安装依赖,在 main.ts 里 app.use(createPinia()) 挂载后,任意页面调用同一个 useXxxStore() 拿到的都是同一份实例。

挂载 ​

ts
// main.ts
import { createSSRApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.uvue'

export function createApp() {
    const app = createSSRApp(App)
    // uni-app x 内置 pinia 3.0.4,项目未安装 pinia 时由编译器自动指向内置运行时
    app.use(createPinia())
    return {
        app
    }
}

不需要安装依赖

createPinia 由编译器解析到 uni-app x 内置运行时,项目里没有 pinia 依赖也能正常编译运行。

定义 Store ​

推荐 setup store 写法:ref 作 state、computed 作 getter、普通函数作 action,最后统一 return。TS 是强类型语言,泛型与返回类型建议写全。

ts
// store/counter.ts
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
    // state
    const name = ref<string>('Pinia')
    const count = ref<number>(0)

    // getters
    const doubleCount = computed((): number => count.value * 2)
    const countText = computed((): string => name.value + ': ' + count.value)

    // actions
    function increment(): void {
        count.value++
    }

    function reset(): void {
        name.value = 'Pinia'
        count.value = 0
    }

    return {
        name,
        count,
        doubleCount,
        countText,
        increment,
        reset
    }
})
组成写法说明
stateref<T>(...)显式写泛型,避免被推断为 any
gettercomputed((): T => ...)标注返回类型
action普通函数函数体内改 ref.value,无需额外包装

在页面中使用 ​

ts
// pages/xxx/index.uvue
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/store/counter.ts'

const counterStore = useCounterStore()
// state / getter 必须经 storeToRefs 解构,直接解构 store 会丢失响应式
const { name, count, doubleCount, countText } = storeToRefs(counterStore)

function increment(): void {
    counterStore.increment()
}

模板里直接使用解包出来的 name、count、doubleCount、countText;修改状态只调 store 上的 action(counterStore.increment()),不要再包一层本地状态。

跨页面共享 ​

store 实例由 pinia 在应用级维护,与页面生命周期无关:

  • 页面 A 调 increment(),页面 B 里 storeToRefs 解出的 count 同步变化,不需要事件总线或路由参数;
  • 页面返回、重建都不会重置状态,只有调用 action 或重新创建应用时才变;
  • 在页面 script setup 顶层调用 useCounterStore() 即可,各页面拿到的是同一个 store。

状态的生命周期

pinia 默认不做持久化,应用重启后状态回到初始值。需要在重启后保留时,自行在 action 里写入本地存储,并在 store 初始化时读回。

演示页 ​

演示页 pages/library/pinia/index.uvue 覆盖了上述三部分:

  • Store 状态:storeToRefs 解包后的 name、count、两个 getter;
  • Actions:increment、decrement、rename、reset 四个按钮,点击后页面上的状态即时刷新;
  • 使用说明:挂载、setup store 写法、storeToRefs 解构、内置版本四条要点。

对应代码片段见演示页 code.ts 的 store、mount、usage 三段,可直接复制运行。

注意事项 ​

  1. const { count } = useCounterStore() 会丢响应式:state 与 getter 必须经 storeToRefs 解构,action 保持方法调用,不要解构。
  2. 不要额外安装 pinia。uni-app x 已内置 3.0.4,自行安装的版本可能与内置运行时不一致。
  3. TS 强类型下,ref<number>()、computed((): number => ...) 的泛型与返回类型建议显式标注,避免推断成 any 后在 App 端编译报错。
  4. store 的 id(defineStore 的第一个参数)在同一应用内必须唯一,重复会复用后注册的定义。