I try to add shopping cart,but I do not know how to do it. When count = 0
, -
is hidden.And when count > 0
, -
is show.When i try to click +
, automatically increase 1, click -
automatically reduced by 1. But can not be displayed. jsfiddle
Look at the Javascript file:
const goods = [{
id: "1",
goods_name: "水立方",
goods_price: "30.00",
goods_num: "15",
count:"0"
}, {
id: "2",
goods_name: "农夫山泉",
goods_price: "28.00",
goods_num: "10",
count:"0"
}]
var app = new Vue({
el: "#app",
data: {
list: goods,
},
methods: {
addCart(item,event) {
if (!this.item.count) {
Vue.set(this.item, 'count', 1);
} else {
this.item.count++;
}
},
lessCart(event) {
this.item.count--;
}
}
})
HTML file:
<div id="app">
<ul>
<li v-for="item in list">
<p>{{item.goods_name}}</p>
<p>{{item.goods_price}}</p>
<a v-show="item.count > 0" @click.stop.prevent="lessCart(item,$event)">-</a>
<input v-show="item.count > 0" v-model="item.count">
<a @click.stop.prevent="addCart(item,$event)">+</a>
</li>
</ul>
</div>
You are mutating the same state each time and not the state from the list.
You should simply do:
const goods = [{ id: "1", goods_name: "水立方", goods_price: "30.00", goods_num: "15", count:"0" }, { id: "2", goods_name: "农夫山泉", goods_price: "28.00", goods_num: "10", count:"0" }] var app = new Vue({ el: "#app", data: { list: goods, }, methods: { addCart(item) { item.count++; }, lessCart(item) { item.count--; } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <ul> <li v-for="item in list"> <p>{{item.goods_name}}</p> <p>{{item.goods_price}}</p> <a v-show="item.count > 0" @click.stop.prevent="lessCart(item)">-</a> <input v-show="item.count > 0" v-model="item.count"> <a @click.stop.prevent="addCart(item)">+</a> </li> </ul> </div>
Note that you do not need the event argument in your method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.