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(命名空間)
爲true
和false
的情況。默認爲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()
])
}
}