Skip to content
On this page

Pinia 数据仓库

pinia是一个集中状态管理容器,可以实现任意组件之间的通信。

核心概念:

  • state 存储数据
  • actions 处理业务
  • getters 计算属性

pinia创建大仓库

首先创建一个大仓库,并在项目中引用。(本项目已经在@dt-frames/pages包中引入。)

js
// 在src/store/index下创建仓库并暴露
import { createPinia } from 'pinia'

export default createPinia()

// 在main.ts中使用
import store from '~store/index'

app.use(store)

pinia支持两种写法:选择式api 和 组合式api,推荐使用组合式api。

选择式api

js
import { defineStore } from 'pinia'

export const useTestStore = defineStore('test', {
    state: () => {
        return {
            count: 99
        }
    },
    actions: {
        test: () => {
            this.count = 123
        }
    },
    getters: {
        getCount(){ return this.count }
    }
})

// 页面使用
const testStore = useTestStore()
console.log(testStore.count)
console.log(testStore.test())

组合式api

js
import { defineStore, StoreDefinition } from 'pinia'
import { Ref, ComputedRef } from 'vue'

/**
 * StoreDefinition有四个参数
 * 参数一:id 仓库id
 * 参数二:存放状态值的类型
 * 参数三:存放计算属性的类型
 * 参数四:存放处理函数的类型
 */

type StoreType = StoreDefinition<
    'test',
    {
        a: Ref
    },
    {
        b: ComputedRef
    },
    {
        c: Function
    }
>

export const useTestStore: StoreType = defineStore('test', () => {
    const a = ref(1)

    const b = computed(() => unref(a))

    function c(str: string) {
        console.log(str)
    }

    return {
        a,
        b,
        c
    }
})

// 使用
const testStore = useTestStore()
console.log(testStore.a)