【问题标题】:How should I structure multiple-use Vue components to load data from different Vuex paths?我应该如何构建多用途 Vue 组件以从不同的 Vuex 路径加载数据?
【发布时间】:2018-08-24 16:23:28
【问题描述】:

我想创建一个组件,我可以多次实例化指向不同的 vuex 命名空间(从中加载其数据)。该组件将从 Vuex 获取大部分数据。所以假设我有一个 Person 组件,我可以根据不同的路径实例化 Person 组件的许多副本到 vuex。

我想出如何做到这一点的最好方法是将 vuex 路径作为道具传递,但是我不知道如何使用 mapGetters 和朋友,因为他们在 .vue 时需要一个命名空间文件被实例化。

我希望能深入了解构建它的最佳“Vue 方式”。这是我目前想出的最接近的方法。

Person.vue:

<template>
    <div>person {{name}} is {{age}} years old</div>
</template>

<script>
  export default {
    props: ['vuexNamespaceToLoadFrom'],

    // FIXME: how do I do a mapGetters with a dynamic namespace that's 
    // set through props???

    // I can't do the following since props aren't in scope yet :-(
    ...mapGetters(this.vuexNamespaceToLoadFrom, [ 'name', 'age'])

  }
</script>

实例化几个从不同 vuex 命名空间加载其属性的 Person 多用途组件:

<Person vuex-namespace-to-load-from="api/jim">
<Person vuex-namespace-to-load-from="api/someotherpath/rachid">
<div>
 <Person vuex-namespace-to-load-from="api/alternatepeople/grace">
</div>

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    这个怎么样?

    人物组件:

    export default (vuexNamespace) => ({
      ...mapGetters(vuexNamespace, ['name', 'age']) 
    })
    

    父组件:

    export default {
      components: {
        Person: Person('someNamespace')
      }
    }
    

    没有测试出来,但我认为它应该可以工作:)

    【讨论】:

    • 我喜欢这个想法,但它不适用于 vue-loader
    • 好像他们没有考虑过这种用法:)好吧,我暂时没有其他想法,抱歉:(
    【解决方案2】:

    为了稍微扩展问题定义,这个

    export default {
      props: ['vuexNamespaceToLoadFrom'],
      ...
      computed: {
        ...mapGetters(this.vuexNamespaceToLoadFrom, [ 'name', 'age'])
      }
    }
    

    是Vue用来创建组件实例的声明性对象,所以不能直接在mapGetters这样的helper中使用实例属性。

    然而,这个讨论Generating computed properties on the fly 展示了一种推迟实例属性评估的方法。

    本质上,在实例完全挂载之前不会评估计算的 get() 的主体,因此对 this.$storethis[namespaceProp] 的引用将在这里起作用。

    根据您的场景进行调整,

    辅助功能

    function mapWithRuntimeNamespace({namespaceProp} = {}, props = []) {
      return props.reduce((obj, prop) => {
        const computedProp = {
          get() {
            return this.$store.getters[this[namespaceProp] + '/' + prop]
          }
        }
        obj[prop] = computedProp
        return obj
      }, {})
    }
    

    用法

    export default {
      props: ['vuexNamespaceToLoadFrom'],
      ...
      computed: {
        ...mapWithRuntimeNamespace(
          { namespaceProp: 'vuexNamespaceToLoadFrom' }, 
          ['name', 'age']
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2021-05-26
      • 2020-05-28
      • 2019-03-12
      • 2019-01-30
      • 2023-01-02
      相关资源
      最近更新 更多