通过 props (Vuex) 传递状态 属性

Pass state property via props (Vuex)

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

<thingy module="module1" section="person">

然后,在组件中:

<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>

问题是,似乎在执行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`);
  }
})

(注意get()是lodash,不是vue函数)

这可以进一步抽象为mixin。

注意 mapState example 中的注释:

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

您正在使用箭头函数。

至于 this.module,我认为您将不得不放弃 binding helper notation 并将模块引用显式放入定义中。我猜它看起来像:

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