vue-demo-购物车
程序员文章站
2022-05-23 08:37:58
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
border: 1px solid #e9e9e9;
border-spacing: 0;
border-collapse: collapse;
}
th,
td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th {
background-color: #f7f7f7;
color: #5c6d77;
}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<th v-for="item in shopTitle">{{item}}</th>
</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="discrement(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价:{{totalPrice}}</h2>
</div>
<div v-else>
<h2>购物车当前为空,快去添加心仪的产品吧</h2>
</div>
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
shopTitle: ['', '书籍名称', '出版日期', '价格', '购买数量', '操作'],
books: [{
id: 1,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 2,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 3,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 4,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
}]
},
methods: {
discrement(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 in this.books) {
totalPrice += this.books[i].price * this.books[i].count;
console.log(i);
}
return totalPrice
}
}
})
</script>
</body>
</html>
上一篇: 用jQuery做一个简单的购物车
下一篇: 过滤器过滤一个包内所有servlet