安装 Pinia
npm i pinia
Pinia 集中式状态管理工具官网 传送门
引入 Pinia
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App);
app.use(pinia);
使用
import { defineStore } from "pinia";
export const useAStore = defineStore('a',{
state(){
return { a:1 }
},
getters: {
doubleCount: (state) => state.a * 2,
},
actions: {
increment(val) {
this.a = val
},
},
})
import { useAStore,storeToRefs } from '@/store/a'
const aStore = useAStore()
aStore.$subscribe((mutate,state) => {
console.log(mutate);
console.log(state);
});
let { a } = storeToRefs(aStore )
console.log(aStore)
aStore.a += 1;
aStore.$patch({
a:2
});
aStore.increment(3)
aStore.doubleCount()
组合式使用
import { reactive, ref } from "vue";
import { defineStore } from "pinia";
export const useAStore = defineStore('a',{
let a = ref('1')
async function addAFun(){
a++
}
return { a,addAFun }
})