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()
])
}
}