Vue3之Pinia(二)

書接上回,我們說到如何修改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ù)......

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容