查看这个简单的购物车演示:
http://plnkr.co/edit/CHt2iNSRJAJ6OWs7xmiP?p=preview
用户可以选择蔬菜和水果,并将其添加到购物车阵列中。添加水果/蔬菜的功能非常相似,我想将其组合为可以在两个组件之间共享的功能。
selectFruit: function(product){
var cart = this.cart
for(p in cart){
if (cart[p]["type"] == "fruit"){
console.log("We already got a fruit!, Let's remove " + cart[p]["name"] + " and add in " + product["name"]);
this.cart.$remove(cart[p])
}
}
console.log("Adding " + product.name + " to cart.");
var productName = product.name
var cartFruit = {name: product.name, type: 'fruit'}
this.cart.push(cartFruit)
}
selectVeggie: function(product){
var cart = this.cart
for(p in cart){
if (cart[p]["type"] == "veggie"){
console.log("We already got a veggie!, Let's remove " + cart[p]["name"] + " and add in " + product["name"]);
this.cart.$remove(cart[p])
}
}
console.log("Adding " + product.name + " to cart.");
var productName = product.name
var cartVeggie = {name: product.name, type: 'veggie'}
this.cart.push(cartVeggie)
}
我该如何做才能更改此方法并使其在全球范围内使用?我正在与此项目一起使用Vue路由器,谢谢您的帮助!