Pinia 的使用

342 阅读1分钟

pina 简介

Store 是保存状态(state)和业务逻辑的实体, store 关键概念 state, getters 和 actions, 这与 Vue 组件中的 data, computed 和 methods 是相对应. 通过defineStore 定义 store, 返回一个函数, 约定将返回值命名为 use...开头

  • defineStore 接收两个参数
    • id: 唯一的标识, string 类型.
    • 第二个参数可以是一个函数, 也可以是一个对象.
  • 第二个参数 为对象的写法:
const useStore = defineStore('id',{
    state: ()=>({
        name: 'linda'
    }),
    getters: {},
    actions: {
       changeName(){
           this.name = 'linda2'
       }
    }
 })
 
// 使用时
const store = useStore()
store.name = 'linda2'
  • 第二个参数为函数时:
 const useStore = defineStore('id', ()=>{
     const name = ref<string>('linda');
     const changeName = ()=>{
      name.value = 'linda2'
     }
     return {
         name,
         changeName
     }
 }) 
 
  • 使用时,如果想结构化数据,使用storeToRefs 创建 ref响应式数据,不能是actions
const store = useStore()
 // 属性对象结构
 const { name } = storeToRefs(useStore());
 // 方法actions结构
 const { changeName } = store

pinia 使用

  • 一种说法: store 不应该与我们的组件绑定.保存的store 应该全局状态.这种是我们日常开发中经常使用的场景。
  • 另一种新型用法: 我们利用pinia 跨组件/页面共享状态 的特性,可以完全替换prop emit页面级组件间传值 的写法。

详细介绍第二种

  • 项目按照页面级设置, 每个页面下都有一个自己的 store, 这样PageA 下的组件共享状态和方法都存到A页面的store 中。举个例子:
    • 页面A 分为 搜索Filter 和表格 Table 两大组件部分
    • 只需要在 store中定义 filterForm、tableData 和 getTableData() 方法。
    • Filter组件绑定store.filterForm, Table 绑定store.tableData。 点击搜索调用store.getTableData()。 省去了组件间互相传值的复杂过程。
    项目目录结构
    -view
       --PageA
          ---components
          ---index.vue
          ---store.ts
       --PageB
           ---components
          ---index.vue
          ---store.ts
        ...

留个疑问,这样的store 什么时候销毁,会自动销毁么?