指定要在组件中使用的 Vuex Store [英] Specify Vuex Store To Use In Component
问题描述
我已经模块化了我的 Vuex 存储,并且需要子组件能够访问数据/使用与其父组件相同的存储.
这是我尝试过的:
<模板><div><子组件vuex-store=服务/机会";/>
</模板><脚本>从 '@/components/services/child-components/ChildComponent' 导入 ChildComponent;import { mapActions, mapState, mapGetters } from 'vuex';导出默认{成分: {'子组件':子组件,},计算:{...mapState('服务/机会', {statusListOpportunities: 'statusListOpportunities',}),}}
<模板><div><!-- 内容-->
</模板><脚本>import { mapActions, mapState, mapGetters } from 'vuex';导出默认{道具: {VuexStore:{类型:字符串,},},计算:{...mapState(this.vuexStore, {statusListOpportunities: 'statusListOpportunities',}),}}
这是我得到的错误
<块引用>未捕获的类型错误:无法读取未定义的属性 'vuexStore'
我一直在传递道具,但是道具杂耍变得混乱,如果我能指定组件应该使用哪个存储会容易得多.
我也无法直接在子组件中指定存储,因为 ParentTwo.vue 可能使用不同的存储,例如 services/cases
.
任何人都知道为什么这行不通.我也愿意接受替代解决方案.
查看下面演示中的 function=myMapState
,用法=...mapState(this.vuexStore, ...)
遇到错误的上下文问题(this
不是组件实例).
一种解决方案是直接访问计算属性函数中的this.$store.state
,就像下面演示中计算属性=test2
所做的那样.
Vue.config.productionTip = false让 myMapState = 函数(选项,测试){!test &&控制台错误(测试)返回 Vuex.mapState(options)}const store = new Vuex.Store({状态: {主题:光",好:真实}})Vue.component('v-test', {模板:`<div><p>1:{{test1}}:{{test2}}</p><p>2:{{theme1}}</p></div>`,道具:['vuexStore'],计算:{...myMapState({'test1': this.vuexStore, 'theme1': 'theme'}, this.vuexStore),测试2:函数(){返回 this.$store.state[this.vuexStore]}}})新的 Vue({el: '#app',店铺})
<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="应用程序"><div><v-test :vuex-store="'theme'"></v-test><v-test :vuex-store="'good'"></v-test>