vuex 的模塊中如何調用 actions 中的方法


vuex 的模塊中如何調用 actions 中的方法  

模塊vuexTest.js

/**
 * 模塊vuexTest.js
 */
export default {
    namespaced: true,
    actions: {
        actionsHello(context, val) {
            console.log(context, "context"); // 與 store 實例具有相同方法和屬性的 context 對象 屬性有 state、getters、rootGetters、rootState、commit、dispatch
            console.log(val, "val"); // 傳的參數
        },
        // actionsHello({ state, getters, rootGetters, rootState, commit, dispatch }, val) { // 才有es6 的解構
        //     console.log(state, "state"); 
        //     console.log(val, "val"); // 傳的參數
        // }
    }
}

1、不使用輔助函數 mapActions 情況下

<!--test.vue-->
<template>
  <div class="vuexRequest">
    vuexRequest
    <el-button @click="change" type="primary">點擊</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    change() {
      this.$store.dispatch("vuexTest/actionsHello", "val123456"); // 前面是指定模塊vuexTest 中的actionsHello 方法,后面是傳參 可以是對象、數組、字符串等
    }
  },
}
</script>

2、適用輔助函數 mapActions 情況下

<!-- test.vue -->
<template>
  <div class="vuexRequest">
    vuexRequest
    <el-button @click="change" type="primary">點擊</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    // 輔助函數的數組形式
    ...mapActions("vuexTest", ["actionsHello"]),
    // 輔助函數的對象形式
    ...mapActions("vuexTest", {
      actionsHello: 'actionsHello'
    }),
    ...mapActions("vuexTest", {
      actionsHello123: 'actionsHello' // 改變模塊vuexTest 中actions 中 方法映射
    }),
    // 方法調用
    change() {
      this.actionsHello("testVal"); // "testVal" 為函數的傳參
      this.actionsHello123("testVal");
    }
  },
}
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM