【问题标题】:Vuex custom name for mapGetters while namespaced is true命名空间为 true 时 mapGetters 的 Vuex 自定义名称
【发布时间】:2021-11-17 09:26:25
【问题描述】:

我想知道当我想给它一个自定义名称并在我的模板中使用这个自定义名称而不是 getter 名称来访问它时,mapGetters 的语法是什么。

const store = createStore({
  modules: {
    prods: productsModule,
    cart: cartModule
  }
});

我的 mapGetters 语法错误: ** ['products'] 是我的 getters 函数名称。

   ...mapGetters({
    prod: 'prods', ['products']
    })

如果我这样做,它可以工作,但我想使用 mapGetters 来做到这一点

products() {
      return this.$store.getters['prods/products'];
}

在我的模板中:

<product-item
    v-for="prod in products"
    :key="prod.id"
    :id="prod.id"
    :title="prod.title"
    :image="prod.image"
    :description="prod.description"
    :price="prod.price"
  ></product-item>

无法在网上找到正确的语法来执行此操作,如果可能,请告诉我。非常感谢!

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    mapGetters(namespace: string, nameLookup: object)

    第一个参数是命名空间名称,第二个参数是对象查找,其中键是要在组件中使用的自定义名称,值是原始 getter 名称。当您想从同一个命名空间映射多个 getter 时,这尤其有用:

    // maps this.myCustomProducts to this.$store.getters['prods/products']
    mapGetters('prods', { myCustomProducts: 'products' })
    

    例子:

    <template>
      <div>
        <product-item v-for="prod in myCustomProducts" />
        <h2>Total: {{ cartTotal }}</h2>
      </div>
    </template>
    
    <script>
    export default {
      computed: {
        ...mapGetters('prods', { myCustomProducts: 'products' }),
        ...mapGetters('cart', { cartTotal: 'total' }),
      }
    }
    </script>
    

    demo 1

    mapGetters(nameLookup: object)

    或者,您可以在查找值中包含命名空间名称,其中原始 getter 名称将以命名空间和斜杠分隔符作为前缀:

    mapGetters({
      myCustomProducts: 'prods/products',
      cartTotal: 'cart/total',
    })
    

    例子:

    <template>
      <div>
        <product-item v-for="prod in myCustomProducts" />
        <h2>Total: {{ cartTotal }}</h2>
      </div>
    </template>
    
    <script>
    export default {
      computed: {
        ...mapGetters({
          myCustomProducts: 'prods/products',
          cartTotal: 'cart/total'
        }),
      }
    }
    </script>
    

    demp 2

    【讨论】:

    • 无论哪种方式都可以。请参阅更新的答案,以将一个 mapGetters 用于多个命名空间模块。
    猜你喜欢
    • 1970-01-01
    • 2020-03-29
    • 2020-06-27
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多