demo功能需求
- 购物车
- 商品可增减数量 该商品总金额自动增减 总金额随之改变
- 搜索商品
- 排序
- 点击按钮随单品金额排序
<div id="example"> <div class="box"> 搜索 <input type="text" v-model="input"> <br> <button @click="orderType=1">点我单价升序</button> <button @click="orderType=2">点我单价降序</button> <button @click="orderType=0">原来单价顺序</button> <div class="container"> <br> <div class="item"> <span> 商品名 </span> <span> 商品数量 </span> <span> 商品金额 </span> <span> 商品总价 </span> </div> <div class="item" v-for="(item,index) in searchData" :key="index"> <span> {{item.name}} </span> <button @click="item.count++">+</button> <span> {{item.count}} </span> <button @click="item.count--" :disabled="item.count<1">-</button> <span> {{item.price | tofixed(2)}} </span> <span> {{item.price*item.count | tofixed(2)}} </span> </div> </div> <br> 所有商品总价 <span>{{count | tofixed(2)}}</span> </div> </div>
js
new Vue({ el: '#example', data: { //数据 items: [{ name: '苹果', price: 10, count: 10 }, { name: '车厘子', price: 109.6, count: 15 }, { name: '火龙果', price: 19.6, count: 3 }, { name: '百香果', price: 9.4, count: 30 }, { name: '橘子', price: 9.4, count: 30 }], input: '', orderType: 0, }, computed: { count() { return this.searchData.reduce(function (prev, current) { return prev + current.price * current.count; }, 0) }, searchData() { let that = this; if (!this.input) return this.items; let data = this.items.filter((item) => { if (item.name.indexOf(that.input) != -1) { return item; } }) if (!that.orderType !== 0) { data.sort((a, b) => { if (that.orderType == 1) { return a.price - b.price; } else { return b.price - a.price; } }) } return data; } }, filters: { tofixed(data, n) { return data.toFixed(n); } } })
...