0👍
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>
Source:stackexchange.com