1. 案例说明:
- 在界面上以表格的形式,显示一些书籍的数据;
- 点击+或者-可以增加或减少书籍数量(如果为1,那么不能继续-);
- 点击移除按钮,可以将书籍移除;
- 在底部显示书籍的总价格;
- 用方法统一显示价格¥;
- 当所有的书籍移除完毕时,显示:购物车为空~。
2. 效果图:
3. 开发过程
3.1 在界面上以表格的形式,显示一些书籍的数据;
| 序号 |
书籍名称 |
出版日期 |
价格 |
购买数量 |
操作 |
| {{index+1}} |
{{item.name}} |
{{item.date}} |
{{item.price}} |
{{item.count}}
|
|
总价:
Vue.createApp({
template: '#shopping',
data: function () {
return {
books: [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
]
}
},
computed: {
},
methods: {
}
}).mount("#app");
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
margin-left: 50%;
transform: translateX(-50%);
}
th,td{
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th{
background-color: #f7f7f7;
color: 5c6b77;
font-weight: 600;
}
.count{
margin: 0px 5px;
}
h2{
text-align: center;
}
3.2 点击+或者-可以增加或减少书籍数量(如果为1,那么不能继续-);
|
{{item.count}}
|
methods: {
sub(index) {
this.books[index].count--;
},
add(index) {
this.books[index].count++;
}
}
3.3 点击移除按钮,可以将书籍移除;
methods: {
sub(index) {
this.books[index].count--;
},
add(index) {
this.books[index].count++;
},
remove(index) {
// 从index开始,切割1位
this.books.splice(index, 1)
}
}
3.4 在底部显示书籍的总价格;
总价:{{total}}
computed: {
total() {
let sum = 0;
for (let book of this.books) {
sum += book.price * book.count;
}
return sum;
}
},
- 3.5 用方法统一显示价格¥;
-
methods: {
sub(index) {
this.books[index].count--;
},
add(index) {
this.books[index].count++;
},
remove(index) {
// 从index开始,切割1位
this.books.splice(index, 1)
},
formatPrice(price) {
return "¥" + price;
}
} //表格价格
| {{formatPrice(item.price)}} |
//总价
总价:{{formatPrice(total)}}
-
- 3.6 当所有的书籍移除完毕时,显示:购物车为空~。
| 序号 |
书籍名称 |
出版日期 |
价格 |
购买数量 |
操作 |
| {{index+1}} |
{{item.name}} |
{{item.date}} |
{{formatPrice(item.price)}} |
{{item.count}}
|
|
总价:{{formatPrice(total)}}
购物车为空~