【问题标题】:Specify Vuex Store To Use In Component指定要在组件中使用的 Vuex 存储
【发布时间】:2021-01-24 23:11:18
【问题描述】:

我已经模块化了我的 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, mapState, mapGetters } from 'vuex';

export default {
    props: {
        vuexStore: {
            type: String,
        },
    },

    computed: {
        ...mapState(this.vuexStore, {
            statusListOpportunities: 'statusListOpportunities',
        }),
    }
}
</script>

这是我遇到的错误

未捕获的类型错误:无法读取未定义的属性“vuexStore”

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

我也无法直接在子组件中指定存储,因为 ParentTwo.vue 可能使用不同的存储,例如 services/cases

任何人都知道为什么这不起作用。我也愿意接受替代解决方案。

【问题讨论】:

  • ...mapState(this.vuexStore, ...) 它应该遇到错误的上下文问题

标签: vue.js vue-component vuex vuex-modules


【解决方案1】:

查看下面demo中的function=myMapState,usage=...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>

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 2018-11-23
    • 1970-01-01
    • 2020-01-27
    • 2021-09-02
    • 2017-08-17
    • 2018-08-10
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多