【发布时间】:2019-01-18 18:08:13
【问题描述】:
我一直在观看一门 Vuex 课程,直到现在一切都很好,直到他们在 getter 中包含箭头函数,然后在计算属性和操作中使用它。代码如下:
项目结构:
const _products = [
{ id: 1, title: "iPad 4 Mini", price: 500.01, inventory: 2 },
{ id: 2, title: "H&M T-Shirt White", price: 10.99, inventory: 10 },
{ id: 3, title: "Charli XCX - Sucker CD", price: 19.99, inventory: 5 }
];
store.js 中的吸气剂:
productIsInStock() {
return product => {
return product.inventory > 0;
};
}
store.js 中使用此 getter 的操作:
addProductToCart(context, product) {
if (context.getters.productIsInStock(product)) {
let cartItem = context.state.cart.find(item => item.id === product.id);
if (!cartItem) {
context.commit("pushProductToCart", product.id);
} else {
context.commit("incrementItemQuantity", cartItem);
}
context.commit("decrementProductInventory", product);
}
},
使用此 getter 和模板的计算,ProductList.vue:
<template>
<li v-for="(product, index) in products" v-bind:key="index">
{{product.title}} - {{product.price | currency}} - {{product.inventory}}
<button
@click="addProductToCart(product)"
:disabled="!productIsInStock(product)"
>
Add product to cart
</button>
</li>
</template>
// ...
computed: {
products() {
return this.$store.state.products;
},
productIsInStock() {
return this.$store.getters.productIsInStock;
}
},
它是完全工作,但我不明白为什么。主要是我不明白这个 getter 在计算和 if 语句中是如何工作的。我试图在控制台中重复相同的结构,但由于某种原因它根本不起作用。希望我提供了足够的代码
【问题讨论】:
-
也许我不清楚你不清楚什么,但该函数需要
product,检查其是否为@987654329 @ 大于0,并返回结果 -true或false。如果有帮助的话,你可以把它想象成productIsInStock = (product) => product.inventory > 0;。 -
@TylerRoper 我不清楚:1)getter 中的箭头函数如何获取值,不只是参数的名称吗? 2)正如我在控制台中看到的,这个getter返回函数我不明白它在if语句中是如何工作的,无论我使用什么具有库存属性的模拟对象,控制台总是返回true,但在控制台之外它工作得很好.我知道这个 getter 过滤结果,但我不明白从语法的角度会发生什么。
标签: javascript vue.js vuex getter arrow-functions