Appearance
带命名空间的绑定函数
本节目标:理解“带命名空间的绑定函数”的核心思路,并能把它用于实际开发或面试表达。 一、常规写法 当使用
mapState,mapGetters,mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐: computed: { ...mapState({ a: state => state.some.nested.module.a, b: state => state.some.nested.module.b }) }, methods: { ...mapActions([ 'some/nested/module/foo', // -> this'some/nested/module/foo' 'some/nested/module/bar' // -> this'some/nested/module/bar' ]) }
二、参数指定命名空间 对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:
computed: { ...mapState('some/nested/module', { a: state => state.a, b: state => state.b })},methods: { ...mapActions('some/nested/module', [ 'foo', // -> this.foo() 'bar' // -> this.bar() ])}三、createNamespacedHelpers 而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
export default { computed: { //在 `some/nested/module` 中查找
...mapState({ a: state => state.a, b: state => state.b }) }, methods: { //在 `some/nested/module` 中查找
...mapActions([ 'foo', 'bar' ]) }}