书接上回,我们说到如何修改store的值:
1.通过store.的方式直接修改
2.通过store.$patch()方法...这次咱们接着说
Action
状态管理,作者认为mutation是冗余的,所以Pinia中并没有mutation,只有action,action既可以处理同步也可以处理异步
// useCart.js
import { defineStore } from 'pinia'
// 第一个参数是应用程序中 store 的唯一 id,就是案例中的"main",类似于vuex的module,好处是不用引入合并了
// 创建store推荐使用"use"开头
export const useCart = defineStore('main', {
// option store写法
// 推荐使用 完整类型推断的箭头函数
state: () => {
return {
// 所有这些属性都将自动推断其类型
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
},
actions:{
// 同步
changeCounter(value){
// 可以通过this直接访问,区别vuex中需要通过state操作
this.counter = value;
},
// 异步:注意这里不要用箭头函数
async getUserName(id){
let res = axios.get(url, {id});
this.name = res;
}
}
})
Action使用
// xxx.vue
<script setup>
import { useCart } from './useCart.js';
const store = useCart();
// 直接通过store.就可以调用,so easy
store.changeCounter(3)
store.getUserName("10086")
</script>
未完待续......