基本配置
main.js
import { createApp } from 'vue'
import {createPinia} from 'pinia'
let vue = createApp(App),
pinia = createPinia();
vue.use(pinia)
vue.mount('#app')
store 文件下
import { defineStore } from 'pinia'
export const useCount = defineStore('useCount', {
state: () => {
return {
count: 1
}
},
actions: {
changeCount(){
this.count+=2
}
},
getters: {
}
})
组件中
获取 / 修改 state
// 事先都需要引入store
import { useCount } from "../../store/index.js"
let countStore = useCount()
// 方法一 (单个处理)
countStore = countStore.count+1
// 方法二 (批量处理) 对象方法
countStore.$patch({
count: countStore.count + 1,
})
// 方法三 (批量处理) 函数方法 接受一个参数,参数为当前state值
countStore.$patch(state=>{
count : state.count++
})
调用actions
import { useCount } from "../../store/index.js";
let countStore = useCount();
countStore.changeCount(2)
调用getters
count10(state){
console.log(state.count , this.count)
return state.count + 10
}