安装 Pinia
js
npm i pinia
引入 Pinia
js
//引入
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App);
app.use(pinia);
使用
js
// store 注册
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 变化
aStore.$subscribe((mutate,state) => {
console.log(mutate); // 行为
console.log(state); // 改变后数据
});
let { a } = storeToRefs(aStore ) //store响应式数据,用于修改实时改变的值
console.log(aStore)
//修改
aStore.a += 1; // 单个
aStore.$patch({ // 批量
a:2
});
aStore.increment(3)
// 获取getter
aStore.doubleCount()
组合式使用
js
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 }
})