書接上回,我們說到如何修改store的值:
1.通過store.的方式直接修改
2.通過store.$patch()方法...這次咱們接著說
Action
狀態(tài)管理,作者認(rèn)為mutation是冗余的,所以Pinia中并沒有mutation,只有action,action既可以處理同步也可以處理異步
// useCart.js
import { defineStore } from 'pinia'
// 第一個參數(shù)是應(yīng)用程序中 store 的唯一 id,就是案例中的"main",類似于vuex的module,好處是不用引入合并了
// 創(chuàng)建store推薦使用"use"開頭
export const useCart = defineStore('main', {
// option store寫法
// 推薦使用 完整類型推斷的箭頭函數(shù)
state: () => {
return {
// 所有這些屬性都將自動推斷其類型
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
},
actions:{
// 同步
changeCounter(value){
// 可以通過this直接訪問,區(qū)別vuex中需要通過state操作
this.counter = value;
},
// 異步:注意這里不要用箭頭函數(shù)
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.就可以調(diào)用,so easy
store.changeCounter(3)
store.getUserName("10086")
</script>
未完待續(xù)......