指定要在组件中使用的Vuex存储

问题描述

我已经对Vuex存储进行了模块化,并且需要子组件才能访问数据/使用与其父组件相同的存储。

这是我尝试过的:

<!-- ParentOne.vue -->
<template>
<div>
  <child-component
    vuex-store="services/opportunities"
  />
</div>
</template>

<script>
import ChildComponent from '@/components/services/child-components/ChildComponent';
import { mapActions,mapState,mapGetters } from 'vuex';

export default {
    components: {
        'child-component': ChildComponent,},computed: {
        ...mapState('services/opportunities',{
            statusListOpportunities: 'statusListOpportunities',}),}
}
</script>
<!-- ChildComponent.vue -->
<template>
<div>
  <!-- Content -->
</div>
</template>

<script>
import { mapActions,mapGetters } from 'vuex';

export default {
    props: {
        vuexStore: {
            type: String,computed: {
        ...mapState(this.vuexStore,}
}
</script>

这是我遇到的错误

未捕获的TypeError:无法读取未定义的属性'vuexStore'

我一直在传递道具,但是道具杂耍变得越来越混乱,如果我仅指定组件应该使用哪个存储,那会容易得多。

我还不能直接在子组件中指定存储,因为ParentTwo.vue可能使用其他存储,例如services/cases

任何人都不知道为什么这行不通。我也欢迎其他解决方案。

解决方法

在下面的演示中查看function = myMapState,用法= ...mapState(this.vuexStore,...)遇到了错误的上下文问题(this不是组件实例)。

一种解决方案是直接使用计算属性的功能访问this.$store.state,就像下面的演示中计算属性= test2一样。

Vue.config.productionTip = false
let myMapState = function (options,test) {
   !test && console.error(test)
   return Vuex.mapState(options)
}
const store = new Vuex.Store({
  state: {
    theme: "light",good: true
  }
})
Vue.component('v-test',{
  template: `<div><p>1: {{test1}}: {{test2}}</p><p>2: {{theme1}}</p></div>`,props: ['vuexStore'],computed: {
    ...myMapState({'test1': this.vuexStore,'theme1': 'theme'},this.vuexStore),test2: function () {
      return this.$store.state[this.vuexStore]
    }
  }
})
new Vue({
  el: '#app',store
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<div id="app">
  <div>
    <v-test :vuex-store="'theme'"></v-test>
    <v-test :vuex-store="'good'"></v-test>
  </div>
</div>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...