1. 程式人生 > 其它 >vuex 的模組中如何呼叫 actions 中的方法

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>