小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
在我们创建好Store实例后,我们在组件中应该怎么使用它呢,我们除了通过$store来获取,还可以通过辅助函数使用,所以这篇来讲讲Store的辅助函数。
辅助函数
mapActions
创建组件方法分发 action。我们在组件中可以使用 this.$store.dispatch('xxx') 分发 action,也可以使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用,如下:
import { mapActions } from 'vuex'
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')`
})
}
}
Action 通常是异步的,那么我们如何知道 action 什么时候结束呢?
我们要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
actions里面
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
使用
store.dispatch('actionA').then(() => {
// ...
})
mapMutations
创建组件方法提交 mutation。类比action我们可以这样使用mapMutations,如下:
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
createNamespacedHelpers
当使用 mapState、mapGetters、mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐,例如有个公共的路径some/nested/module,我们就可以这样使用:
computed: {
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('some/nested/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}
总结
我们需要注意的是:mapState、mapGetters是作用在computed里面,而mapActions 和 mapMutations是作用在methods里面。
想了解更多文章,传送门已开启:回首Vue3目录篇 !