Vuex:通过道具传递状态属性

Chr*_*tof 5 vue.js vuex

我有一个组件应该显示来自商店的数据,但该组件是可重用的,所以我想通过道具传递商店模块的名称和属性名称,如下所示:

<thingy module="module1" section="person">
Run Code Online (Sandbox Code Playgroud)

然后,在组件中:

<template>
    <h2>{{ title }}</h2>
    <p>{{ message }}</p>
</template>

<script>
  import { mapState } from 'vuex'
  import get from 'lodash.get'

  export default {
    props: [
      'module',
      'section'
    ],
    computed: mapState(this.module, {
      title: state => get(state, `${this.section}.title`),
      message: state => get(state, `${this.section}.message`)
    })
  }
</script>
Run Code Online (Sandbox Code Playgroud)

问题是,似乎道具在mapState()执行时未定义。如果我对 prop 值进行硬编码,则组件可以工作。此外,如果我在created()钩子中记录道具,我会得到预期值。所以这似乎是一个竞争条件。

我在这里以错误的方式解决这个问题吗?

更新

模块命名空间必须从映射函数内部传递,如下所示:

computed: mapState({
  title() {
    return get(this.$store.state, `${this.module}.${this.section}.title`)
  },
  message() {
    return get(this.$store.state, `${this.module}.${this.section}.message`)
  }
})
Run Code Online (Sandbox Code Playgroud)

(请注意,这get()是一个 lodash,而不是一个 vue 函数)

这可以进一步抽象为mixin。

Roy*_*y J 3

请注意以下评论mapState example

// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
  return state.count + this.localCount
}
Run Code Online (Sandbox Code Playgroud)

您正在使用箭头函数。

至于this.module,我认为您将不得不放弃绑定辅助符号并显式地将模块引用放入定义中。我猜这看起来像:

computed: mapState(this.module, {
  title(state) {
    return get(`${state}.${this.module}`, `${this.section}.title`);
  },
  message(state) {
    return get(`${state}.${this.module}`, `${this.section}.message`);
  }
})
Run Code Online (Sandbox Code Playgroud)