- 以mapActions為例,通常,我們?cè)趘uex的actions中定義一個(gè)方法:
export default {
vuexSetUserLogin({commit}){
commit("vuex_set_user_login");
},
vuexSetTest({commit}, val){
commit("vuex_set_test", val);
}
}
調(diào)用時(shí)這樣調(diào)用:
this.$store.dispatch("vuexSetTest", "ttttttt");
- mapActions的作用就是,把a(bǔ)ctions中的方法映射到methods中,換一種調(diào)用方式。
引入mapAction:
import {mapActions,} from 'vuex'
映射方法:
"methods": {
...mapActions([
"vuexSetUserLogin",
"vuexSetTest"
]),
},
把a(bǔ)ctions里面的兩個(gè)方法映射到本地的同名方法
調(diào)用的時(shí)候就像調(diào)用本組件的method一樣:
this.vuexSetTest("eeee");
- mapActions() 返回的是一個(gè)對(duì)象, 用了 ... 擴(kuò)展符后,才可以放進(jìn)一個(gè)對(duì)象里,和其他組件內(nèi)定義的 method 在同一個(gè) methods 對(duì)象。
{
methods: mapActions() // 如果沒有其它組件內(nèi)的定義的方法,可以這樣寫
}
{
methods: {
...mapActions(),// 如果有其他定義的方法
otherMethod1 () {},
otherMethod2 () {}
}
}
- mapGetters:
computed:mapGetters([
'count'
]),
- 映射的時(shí)候可以取別名:
export default {
// ...
methods: {
//下述中的 ... 是拓展運(yùn)算符
// 使用 [] 是解構(gòu)賦值
...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')`
})
}