Vuex 使用actions中的方法(包括module中的actions)

1.直接store中dispatch
export default {
  methods: {
    clickFn() {
      this.$store.dispatch("sampleFn") //不帶參
      this.$store.dispatch("withParamFn",param) //帶參,param爲參數
    }
  }
};
2.使用mapActions取值
import { mapActions } from "vuex";

export default {
  methods: {
    ...mapActions([
      "sampleFn", // 將 `this.sampleFn()` 映射爲 `this.$store.dispatch('sampleFn')`
      "withParamFn" // 將`this.withParamFn(param)`映射爲`this.$store.dispatch('withParamFn', param)`
    ]),
    ...mapActions({
      newFn: "sampleFn" // 將`this.newFn()`映射爲`this.$store.dispatch('sampleFn')`
    }),
  }
 }
3.使用module中的actions

module中的actions,又分爲namespaced(命名空間)truefalse的情況。默認爲false,則表示方位都是全局註冊,與上邊兩種方法一致。當爲true時,則使用如下方法:

import { mapState, mapActions } from "vuex";

export default {
  methods: {
    ...mapActions([
      "moduleA/sampleFn" // -> this['moduleA/sampleFn']()
    ]),
    ...mapActions("moduleA", [
      "sampleFn" // -> this.sampleFn()
    ]),
    clickFn() {
      this.$store.dispatch("moduleA/sampleFn"); // 直接從store中dispatch
    }
  }
};

// 使用createNamespacedHelpers函數
import { createNamespacedHelpers } from "vuex";
const { mapActions } = createNamespacedHelpers("moduleA");

export default {
  methods: {
    ...mapActions([
      "sampleFn" // -> this.sampleFn()
    ])
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章