【发布时间】:2017-08-17 11:47:11
【问题描述】:
我有一个组件应该显示来自 store 的数据,但该组件是可重用的,所以我想通过 props 传递 store 模块的名称和属性名称,如下所示:
<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。
【问题讨论】:
标签: javascript vue.js vue-component vuex vue-props