【问题标题】:Vuex - dynamic namespaces in binding helpers (mapState, ...)Vuex - 绑定助手中的动态命名空间(mapState,...)
【发布时间】:2019-09-19 12:00:13
【问题描述】:

我正在动态注册 vuex 存储模块

store.registerModule('home.grid', GridStore)

然后在组件中:

export default {
name: 'GridComponent',

props: {
  namespace: {
    type: String,
    required: true
  },

 computed: {
    ...mapState(this.namespace, ['filter']) // doesn't work
    filter() { // more verbose but working
      return this.$store.state[this.namespace].filter
    }
 }
 ...

但我得到了错误:

无法读取未定义的属性“命名空间”

有什么想法吗?

问题最初来自“gabaum10”https://forum.vuejs.org/t/vuex-dynamic-namespaces-in-mapstate-mapactions/28508

【问题讨论】:

  • gabaum10 似乎也在同一个线程中找到了答案。这不适合你吗?

标签: vuex


【解决方案1】:

另一种方法可能是利用计算属性在数据属性之后初始化的事实。但这仅适用于计算属性 - 因为方法是在数据之前计算的。

一个例子:

export default {
  props: {
    namespace: {
      type: String,
      required: true
    },
  },
  data(){
    // Append more computed properties before they are initialized.
    this.$options.computed = {
      ...this.$options.computed,
      ...mapState(this.namespace, ['filter'])
    }

    return {
      foo: bar
    }
  },

}

【讨论】:

  • 这行得通吗?我收到一个错误:[vuex] mapActions: mapper parameter must be either an Array or an Object
  • 哦,对了。这就是我一直在搞砸的。谢谢
【解决方案2】:

在这里解决https://github.com/vuejs/vuex/issues/863#issuecomment-329510765

{
  props: ['namespace'],

  computed: mapState({
    state (state) {
      return state[this.namespace]
    },
    someGetter (state, getters) {
      return getters[this.namespace + '/someGetter']
    }
  }),

  methods: {
    ...mapActions({
      someAction (dispatch, payload) {
        return dispatch(this.namespace + '/someAction', payload)
      }
    }),
    ...mapMutations({
      someMutation (commit, payload) {
        return commit(this.namespace + '/someMutation', payload)
      })
    })
  }
}

【讨论】:

  • 你救了我的命
【解决方案3】:

我在制作动态 getter 时基本上遇到了完全相同的问题,由于某种原因,您不能使用来自组件的数据变量来执行 vuex 映射函数。

所以这对我不起作用

 ...mapGetters( this.layout,['getFilterByObject'])

但我可以这样做

this.$store.getters[this.layout + '/getFilterByObject'](filterGroup)

也许你可以做某事。和你的状态差不多,不过我没测试过

this.$store.state[this.namespace].filter

【讨论】:

  • 是的,它在没有任何绑定助手(mapState、mapMutations)的情况下工作得很好:this.$store.state[this.namespace].filter。但它使代码更加冗长!
  • 是的,您是对的,感谢您分享您的解决方案!我希望 vuex 文档更详细一点。
猜你喜欢
  • 2020-03-29
  • 2018-01-17
  • 2019-07-02
  • 2013-12-06
  • 2018-12-31
  • 2019-06-23
  • 1970-01-01
  • 2015-03-09
相关资源
最近更新 更多