大家好,刚刚在vue中练习。我在 vuex 中遇到了 getter 的一种奇怪行为——如果将 find 方法应用于其中的数组,代码将无法工作。
所以这是我来自 Vuex 的 products.js 模块:
export default {
namespaced: true,
state: {
items: getProducts()
},
getters: {
items(state){
return state.items;
},
mapProducts(state){
let mapArr = [];
for(let i = 0; i < state.items.length; i++){
mapArr[state.items[i].id_product] = state.items[i];
}
return mapArr;
},
get_product_by_id: (state, getters) => (id) => {
return getters.items.find((elem) => {
return elem.id_product === id;
})
},
item: (state, getters) => (id) => {
return getters.mapProducts[id];
}
}
}
function getProducts(){
return [
{
id_product: 14,
name: "Xiaomi Mi 9T Pro",
desc: "Android, экран 6.39\" AMOLED (1080x2340), Qualcomm Snapdragon 855, ОЗУ 6 ГБ, флэш-память 128 ГБ, камера 48 Мп, аккумулятор 4000 мАч, 2 SIM",
price: 520,
img: require('../../assets/img/id14.jpg')
},
{
id_product: 17,
name: "HONOR 20",
desc: "Android, экран 6.26\" IPS (1080x2340), HiSilicon Kirin 980, ОЗУ 6 ГБ, флэш-память 128 ГБ, камера 48 Мп, аккумулятор 3750 мАч, 2 SIM",
img: require('../../assets/img/id17.jpeg'),
price: 350
}
]
}
这是我的 Product.vue 组件,我试图通过其 id 获取产品对象:
<template>
<div>
<h1>{{ get_product }} - {{ get_product_id }}</h1>
</div>
</template>
<script>
import {mapGetters} from 'vuex';
export default {
name: "Product",
data() {
return { }
},
computed: {
...mapGetters("products", {
get_product_by_id: "get_product_by_id",
item: "item"
}),
get_product_id(){
return this.$route.params.id;
},
get_product(){
console.log(this.get_product_by_id(this.get_product_id)); // В консоли undefined
return this.get_product_by_id(this.get_product_id); // Не работает и все тут
//return this.get_product_by_id(19); // Так работает!!!
//return this.item(this.get_product_id); // Так тоже работает!!!
}
},
methods: { }
}
</script>
正如您从评论中看到的那样,在计算中,在 get_product 方法中,行
return this.get_product_by_id(this.get_product_id);
断然拒绝工作,当您尝试将结果输出到控制台时,它会写入未定义。
但是,如果您致电:
return this.get_product_by_id(19);
然后我成功获得了产品对象。还成功返回我一个产品对象调用:
return this.item(this.get_product_id);
解释调用问题
return this.get_product_by_id(this.get_product_id);
为什么应该工作的时候却不工作!!!
问题是从查询字符串中, id 路由参数以字符串形式出现。这可以通过在 id 和输出到 console.log() 之前添加 typeof 运算符来检查 - 我们得到一个字符串。而 this.get_product_by_id() 方法需要 id 作为数字。该问题可以通过将 id 转换为数字来解决,如下所示: