遗弃传统的Mutation,只有state,getter和action,简化状态管理库
首先创建store
import {defineStore} from 'pinia'
export const mainStore = defineStore('main', {
state: () => {
return {
msg: 'hello world'
}
},
getters: {// getter的值具有缓存性,如果值没有改变,多次使用也只会调用一次
getCountBuff(state) {
return `${state.count}次`
}
}
actions: {
changeState() {
this.count ++
this.msg = ...
}
}
})
使用时:
import {mainStore} from '../store/index'
import {storeToRefs} from 'pinia'
const store = mainStore()
// 获取值
const {count} = store // ES传统方式解构(能获取到值,但是不具有响应性)
cosnt {count} = storeToRefs(store) // Pinia解构方法:storeToRefs
// 修改值
const addOne = () => {
store.count++
}
// $patch + 对象
const onObjClick = () => {
store.$patch({
count: store.count + 2
})
}
// $patch + 函数
const onFunClick = () => {
store.$patch((state) => {
state.count = state.count + 2
})
}
// 通过action修改
const addOne = () => {
store.changeState()
}