问题
I have modularized my Vuex store and need child-components to be able to access data/use the same stores as their parent component.
Here's what I've tried:
<!-- 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, mapState, mapGetters } from 'vuex';
export default {
props: {
vuexStore: {
type: String,
},
},
computed: {
...mapState(this.vuexStore, {
statusListOpportunities: 'statusListOpportunities',
}),
}
}
</script>
And here's the error I'm getting
Uncaught TypeError: Cannot read property 'vuexStore' of undefined
I've been passing down props, but the prop juggling is getting chaotic and it would be much easier if I could just specify which store a component should use.
I also not able to specify the store directly in the child component since ParentTwo.vue may use a different store such as services/cases
.
Anyone have any idea why this wouldn't work. I'm open to alternative solutions as well.
回答1:
Look into the function=myMapState
in below demo, the usage=...mapState(this.vuexStore, ...)
encountered wrong context issue (this
is not the component instance).
One solution is directly access this.$store.state
in the function of computed property as what computed property=test2
does in below demo.
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>
来源:https://stackoverflow.com/questions/64287347/specify-vuex-store-to-use-in-component