选项式

  1. 新建一个Store文件夹

  2. 新建[name].ts文件

  3. 定义仓库Store

       import { defineStore } from 'pinia'
    
  4. 我们需要知道存储是使用定义的defineStore(),并且它需要一个唯一的名称,作为第一个参数传递 名称可以单独抽离出来store-namespace/index.ts。

    export const enum Names {
        Test = 'TEST'
    }
    

    store 引入

    import { defineStore } from 'pinia'
    import { Names } from './store-namespace'
     
    export const useTestStore = defineStore(Names.Test, {
     
    })
    
  5. 定义值

    import { defineStore } from 'pinia'
    import { Names } from './store-namespce'
     
    export const useTestStore = defineStore(Names.Test, {
         // State 箭头函数 返回一个对象 在对象里面定义值
         state:()=>{
             return {
                 current:1
             }
         },
         //类似于computed 可以帮我们去修饰我们的值
         getters:{
     
         },
         //可以操作异步 和 同步提交state
         actions:{
     
         }
    })
    

组合式

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }
  return { count, doubleCount, increment }
})

在 Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions
Last Updated:
Contributors: haizhiguang