- 以mapActions为例,通常,我们在vuex的actions中定义一个方法:
export default {
vuexSetUserLogin({commit}){
commit("vuex_set_user_login");
},
vuexSetTest({commit}, val){
commit("vuex_set_test", val);
}
}
调用时这样调用:
this.$store.dispatch("vuexSetTest", "ttttttt");
- mapActions的作用就是,把actions中的方法映射到methods中,换一种调用方式。
引入mapAction:
import {mapActions,} from 'vuex'
映射方法:
"methods": {
...mapActions([
"vuexSetUserLogin",
"vuexSetTest"
]),
},
把actions里面的两个方法映射到本地的同名方法
调用的时候就像调用本组件的method一样:
this.vuexSetTest("eeee");
- mapActions() 返回的是一个对象, 用了 ... 扩展符后,才可以放进一个对象里,和其他组件内定义的 method 在同一个 methods 对象。
{
methods: mapActions() // 如果没有其它组件内的定义的方法,可以这样写
}
{
methods: {
...mapActions(),// 如果有其他定义的方法
otherMethod1 () {},
otherMethod2 () {}
}
}
- mapGetters:
computed:mapGetters([
'count'
]),
- 映射的时候可以取别名:
export default {
// ...
methods: {
//下述中的 ... 是拓展运算符
// 使用 [] 是解构赋值
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
网友评论