gpt4 book ai didi

vue.js - 命名空间为 true 时 mapGetters 的 Vuex 自定义名称

转载 作者:行者123 更新时间:2023-12-05 03:37:27 25 4
gpt4 key购买 nike

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

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>

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

最佳答案

mapGetters(命名空间:字符串,nameLookup:对象)

第一个参数是命名空间名称,第二个参数是对象查找,其中键是要在组件中使用的自定义名称,值是原始的 getter 名称。当您想要从同一 namespace 映射多个 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: 对象)

或者,您可以在查找值中包含命名空间名称,其中原始 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

关于vue.js - 命名空间为 true 时 mapGetters 的 Vuex 自定义名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69309172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com