在map中使用的值,在mapState中使用不能正常工作Vue.js

问题描述 投票:0回答:1

我想从props传递值并将其用作mapState中的命名空间,然后显示错误:'初始化应用程序时出错TypeError:无法读取属性'store'of undefined'这里我的代码:

ParentComponent:<Editor store="store-test" />

子组件:

export default {
    props: ['store'],
    computed: {
        mapState(`${this.store}`, ['data'])
    }
}

但我取代this.store = store-test,我收到了我想要的数据。我不知道如何使用

...mapMutations({
  function() {
  }
})

是一样的

...mapState({
  data(state) {
    return state[this.store].data;
  },
})
vue.js vuex
1个回答
1
投票

因为mapState在编译时返回其computed定义的值,所以不能使用props,因为它们仅在运行时分配。

你将不得不使用

computed: {
  data () {
    return this.$store.state[this.store].data
  }
}

如果需要,您仍然可以使用mapState,但不能将prop值用作命名空间字符串

mapState({
  data1 (state) { // 👈 note: cannot be an arrow function
    return state[this.store].data1
  },
  data2 (state) {
    return state[this.store].data2
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.