代码放到码云上了,可以自己拉取:https://gitee.com/cxy-xupeng/vue-test.git
作为后端程序员,你如何认真看了前两章的内容,那么这边的小练习来看看吧
一、小练习1
对于一个数组列表,我们点谁,就让谁红。
分析:首先需要遍历列表。其次,点谁让谁红那么肯定是要能获取每条列表数据,也就是需要列表的序号。第三,肯定也是需要点击事件。第四,需要一个style
二、小练习二
1.对于一个图书购物车,你点击”+”,那本书数量+1,总价加上那本书的金额。“-”同理。
2.点击移除,那本书移除。
3.如果整个购物车没有图书,显示一行文字
我们先来搭一个架子:
下面我们开始处理一些细节:
(1)价格得保留两位小数,而且前面还有一个¥。'¥'+price.toFixed(2)
这里设置价格也有两种方法
1)我们之前学的方法
js里
html里:
2)过滤器
js里:
html里:
(2)价格里面的“+”和“-”
1)点击对应的数字要跟着变化
2)变成1之后应该不能再减少
(3)点击移除,要删除那一行数据。并且显示一行文字
(4)显示最终价格
至此,我们的代码就算完成了:
完整代码:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!-- 引入style.css -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(book,index) in books">
<td>{
{book.id}}</td>
<td>{
{book.name}}</td>
<td>{
{book.date}}</td>
<td>
<button @click="decrement(index)" :disabled="book.count<=1">-</button>
{
{book.price | showPrice}}
<button @click="increment(index)">+</button>
</td>
<td>{
{book.count}}</td>
<td>
<button @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{
{totalPrice | showPrice}}</h2>
</div>
<div v-else>购物车为空</div>
</div>
<!-- 引入js -->
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
const app = new Vue({
el:"#app",
data:{
books:[
{
id:1,
name:'java',
date:'2020-11',
price:85.00,
count:1
},
{
id:2,
name:'linux',
date:'2020-11',
price:59.00,
count:1
},
{
id:3,
name:'python',
date:'2020-11',
price:39.00,
count:1
},
{
id:4,
name:'java',
date:'2020-11',
price:128.00,
count:1
}
]
},
methods:{
/* getFinalPrice(price){
return '¥'+price.toFixed(2)
} */
decrement(index){
this.books[index].count--
},
increment(index){
this.books[index].count++
},
removeHandle(index){
this.books.splice(index,1)
}
},
filters:{
showPrice(price){
return '¥'+price.toFixed(2)
}
},
computed:{
totalPrice(){
let totalPrice =0
for(let i = 0;i<this.books.length;i++){
totalPrice += this.books[i].count * this.books[i].price
}
return totalPrice
}
}
})
style.css
table{
border:1px solid #e9e9e9;
/* border-collapse 属性设置表格的边框是否被合并为一个单一的边框,还是象在标准的 HTML 中那样分开显示。 */
border-collapse: collapse;
/* border-spacing 属性设置相邻单元格的边框间的距离 */
border-spacing: 0;
}
th,td{
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}