Vue.js学习第四天——购物车案例
实现的大致效果如下图:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div id="container">
<table class="table table-striped table-hover" align="center" id="box">
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for='i in id' v-if='isShow[i]'>
<td>{{i+1}}</td>
<td>{{books[i]}}</td>
<td>{{date[i]}}</td>
<td>¥{{price[i]}}</td>
<td>
<button style="width: 30px;height:30px;" @click='UnAdd(i)'
v-bind:disabled='counter[i]<=1'>-</button>
<p style="display:inline-block">{{counter[i]}}</p>
<button style="width: 30px;height:30px;" @click='Add(i)'>+</button>
</td>
<td>
<button @click='remove(i)'>移除</button>
</td>
</tr>
</table>
<p>总价:¥ {{total}}</p>
</div>
<script src="./vue.js"></script>
<script>
const app = new Vue({
el: '#container',
data: {
id: [0, 1, 2, 3],
counter: [1, 1, 1, 1],
price: [85.00, 59.00, 39.00, 128.00],
books: ['《《算法导论》》', '《《UNIX编程艺术》》', '《《编程珠玑》》', '《《代码大全》》'],
date: ['2006-9', '2006-2', '2008-10', '2006-3'],
isShow: ['true', 'true', 'true', 'true']
},
computed: {
total() {
let finalPrice = 0;
for (let i = 0; i <= 3; i++) {
finalPrice = finalPrice + this.counter[i] * this.price[i];
}
return finalPrice;
}
},
methods: {
Add(i) {
++this.counter[i];
this.counter.splice(i, 1, this.counter[i]++);
},
UnAdd(i) {
--this.counter[i];
this.counter.splice(i, 1, this.counter[i]--);
},
remove(i) {
this.isShow[i] = !this.isShow[i];
this.isShow.splice(i, 1, this.isShow[i]);
}
}
})
</script>
</body>
</html>
本次案例由于是我自己写的,没有按照老师的写法,所以出现了一些问题,不过收获还是有的,这里记录一下。
没有实现的功能:总价在进行移除操作后,是没办法减去移除元素价格的。
在看了老师的写法后,才发现是数据结构的问题,老师的数据是在一个大的数组中放了4个对象,每个对象存入书的名称,价格等等,这样一来在获取数据方面就方便得多了,而我把它放在数组中,所以没有实现的功能基本上是无解的,这才意识到数据结构的重要性。另外还有几个补充知识点:
- 过滤器,在上面的案例中,价格前面有一个$符号,我采用的是拼接的方式,但是这样的方式对纯数据来说不太友好,所以引入过滤器,filters,本质上还是几个函数;
- 对数据的处理的一个方法 toFixed(numer) number表示要添加几个小数零;
- 为按钮绑定disabled后,按钮不能进行点击,见上面的代码即可。
在做这个案例的时候,一开始没有注意前面那个数组中的非响应式的方法,耽误了比较多的时间,后来才发现转为splice方法,下次要注意一下。