首页 文章

Vuex:通过道具传递州 property

提问于
浏览
3

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

<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() 钩子中记录道具,我会得到预期的值 . 所以这似乎是一种竞争条件 .

我在这里走错了路吗?

Update

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

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 .

1 回答

  • 3

    请注意mapState example中的注释:

    //使用this访问本地状态,必须使用普通函数
    countPlusLocalState(state)

    您正在使用箭头功能 .

    至于 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`);
      }
    })
    

相关问题