[英]Adding item to cart and removing from cart
I have a + button to add item to cart,it works.我有一个 + 按钮可以将商品添加到购物车,它可以工作。 But at the same time when number increments in cart I need number that says in stock will decrement number in stock that displays it doesn't work …但与此同时,当购物车中的数字增加时,我需要显示库存的数字将减少库存的数字,显示它不起作用……
I need to do the same with - button我需要对 - 按钮做同样的事情
I really need the displayed inStock
number to change when I add or remove items from cart Can someone please help me?当我从购物车中添加或删除商品时,我真的需要更改显示的inStock
编号 有人可以帮我吗? I'm new at this我是新手
Vue.component('product', {
template:
`
<div class="product">
<div class="product-image">
<img :src="image" />
</div>
<div class="product-info">
<h1>{{ product }}</h1>
<p v-if="inStock">In Stock {{inStock}}</p>
<p v-else>Out of Stock</p>
<button @click="addToCart"
:disabled="!inStock"
:class="{ disabledButton: !inStock }"> + </button>
<button @click="removeFromCart"> - </button>
</div>
</div>
`,
data() {
return {
product: 'Hoodie',
image: 'hoodie.jpeg',
inStock: 10,
cart: 0
}
},
methods: {
addToCart: function() {
this.$emit('add-to-cart')
},
removeFromCart: function() {
this.$emit('remove-from-cart')
}
}
})
var app = new Vue({
el: '#app',
data: {
cart: 0,
inStock: 10
},
methods: {
updateCart() {
this.cart += 1,
this.inStock -= 1,
},
removeItem() {
this.cart -= 1,
this.inStock += 1
}
}
})
HTML: HTML:
<div class="nav-bar"></div>
<div id="app">
<div class="cart">
<p>Cart({{ cart }})</p>
</div>
<product @add-to-cart="updateCart" @remove-from-cart="removeItem"></product>
</div>
Inside your component, remove the data attributes inStock
and cart
and props
section.在您的组件内,删除数据属性inStock
和cart
和props
部分。
Vue.component('product', {
template:
`
<div class="product">
<div class="product-image">
<img :src="image" />
</div>
<div class="product-info">
<h1>{{ product }}</h1>
<p v-if="inStock">In Stock {{inStock}}</p>
<p v-else>Out of Stock</p>
<button @click="addToCart"
:disabled="!inStock"
:class="{ disabledButton: !inStock }"> + </button>
<button @click="removeFromCart"> - </button>
</div>
</div>
`,
data() {
return {
product: 'Hoodie',
image: 'hoodie.jpeg',
}
},
props: {
inStock: {
type: Number,
default: 0
},
cart : {
type: Number,
default: 0
}
},
methods: {
addToCart: function() {
this.$emit('add-to-cart')
},
removeFromCart: function() {
this.$emit('remove-from-cart')
}
}
})
var app = new Vue({
el: '#app',
data: {
cart: 0,
inStock: 10
},
methods: {
updateCart() {
this.cart += 1,
this.inStock -= 1,
},
removeItem() {
this.cart -= 1,
this.inStock += 1
}
}
})
Then in your parent component, pass the props.然后在您的父组件中,传递道具。
Parent Component (HTML)父组件 (HTML)
<div class="nav-bar"></div>
<div id="app">
<div class="cart">
<p>Cart({{ cart }})</p>
</div>
<!-- changes for props added below -->
<product :cart="cart" :inStock="inStock" @add-to-cart="updateCart" @remove-from-cart="removeItem"></product>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.