购物车模块实现功能:商品数量的增减,商品价格的实时变化,商品的删除等。
css
* {
margin: 0;
padding: 0;
}
table {
border: 1px solid blueviolet;
/* border-collapse 合并为一个单一的边框 */
border-collapse: collapse;
/*border-spacing 相邻单元格的边框间的距离 */
border-spacing: 0;
}
td {
padding: 8px 16px;
border: 1px solid rosybrown;
text-align: left;
}
thead th {
background-color: sienna;
font-weight: 700;
}
html
<div id="cart">
<div v-if="books.length > 0">
<table>
<thead>
<td> </td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="sub(index)">-</button>
<span>{{item.count}}</span>
<button @click="add(index)">+</button>
</td>
<td>
<button @click="removeBook(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<h1>总价格为:{{totalPrice | showPrice}}</h1>
</div>
<div v-else>购物车为空</div>
</div>
js
本人由于初学vue,所有使用这种简单的引入vuejs的方法
<script src="./vue.js"></script>
<script>
const cart = new Vue({
el: "#cart",
data: {
books: [{
id: 1,
name: "《小红帽》",
date: "2009-2-1",
price: 34.00,
count: 1
}, {
id: 2,
name: "《围城》",
date: "2018-11-2",
price: 85.00,
count: 1
}, {
id: 3,
name: "《毛泽东思想》",
date: "2012-2-21",
price: 167.00,
count: 1
}, {
id: 4,
name: "《近代史纲要》",
date: "2015-4-4",
price: 56.00,
count: 1
}, {
id: 5,
name: "《算法导论》",
date: "2001-12-9",
price: 39.00,
count: 1
}]
},
methods: {
sub(index) {
if (this.books[index].count > 1) {
this.books[index].count--;
}
},
add(index) {
this.books[index].count++;
},
removeBook(index) {
this.books.splice(index, 1)
}
},
computed: {
totalPrice() {
return this.books.reduce((pre, book) => {
return pre + book.price * book.count
}, 0)
}
},
filters: {
showPrice(price) {
return "¥" + price.toFixed(2)
}
}
})
</script>
效果如图
一个案例,满满的知识!!!
css
border-collapse 合并为一个单一的边框
border-spacing 相邻单元格的边框间的距离
JavaScript vuejs
- v-if判断
- v-on(语法糖@) 事件绑定
- v-for 循环
- computed计算属性 (计算属性是一个属性,在使用时不需要加())
- filters 过滤器
- 高阶函数reduce
- 箭头函数
- 数组的splice方法(具体使用见下一篇文章)