Vue教程购物车案例
Posted _否极泰来_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue教程购物车案例相关的知识,希望对你有一定的参考价值。
Vue教程(十二)购物车案例
代码实现
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<title>购物车案例</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<h3>====欢迎光临《我行我素商城》购物车案例===</h3>
<div id="app">
<div v-if="books.length > 0">
<table border="1" width="40%">
<thead>
<tr>
<th>序号</th>
<th>编号</th>
<th>书籍</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.isbn}}</td>
<td>{{item.name}}</td>
<td>{{item.price | formatPrice(item.price)}}</td>
<td>
<button @click="decrement(index)" v-bind:disabled="books[index].number<=1">-</button>
{{item.number}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeBook(index)">移除</button></td>
</tr>
</tbody>
</table>
<h3>已选择1件商品总价:{{totalPrice | formatPrice(totalPrice)}}</h3>
</div>
<div v-else>
<h3>购物车暂无商品,快去购物吧~</h3>
</div>
</div>
<script>
const app = new Vue({
el:"#app",
data:{
books:[
{id:1,isbn:11144230,name:"算法导论(原书第3版)",price:105.60,number:1},
{id:2,isbn:11993134,name:"Python编程 从入门到实践 第2版(图灵出品)",price:50.00,number:1},
{id:3,isbn:12392810,name:"计算机网络:自顶向下方法(原书第7版)",price:73.40,number:1},
{id:4,isbn:12586331,name:"离散数学及其应用(原书第8版) ",price:123.30,number:1},
{id:5,isbn:12006637,name:"深入理解计算机系统(原书第3版)",price:114.60,number:1},
]
},
methods:{
decrement:function (index){
this.books[index].number--;
},
increment:function (index){
this.books[index].number++;
},
removeBook:function (index){
this.books.splice(index,1);
}
},
computed: {
totalPrice() {
// let totalPrice = 0;
// for (let book of this.books) {
// totalPrice += book.price * book.number;
// }
// return totalPrice;
return this.books.reduce((prev, book) => prev + book.price * book.number,0);
}
},
filters:{
formatPrice:function (price){
return "¥" + price.toFixed(2)+"元";
}
}
});
const nums = [10,20,111,222,444,40,50];
let total = nums.filter(n => n <100).map(n => n * 2).reduce((p,n)=> p+n);
console.log("--------------",total);
</script>
</body>
</html>
– 以上为《Vue教程(十二)购物车案例》,如有不当之处请指出,我后续逐步完善更正,大家共同提高。谢谢大家对我的关注。
——厚积薄发(yuanxw)
以上是关于Vue教程购物车案例的主要内容,如果未能解决你的问题,请参考以下文章