demo738.html
<!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>
</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="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.data}}</td>
<td>{{item.price|getFinal}}</td>
<td>
<button @click="increment(index)">+</button> {{item.count}}
<button @click="decrement(index)" v-bind:disabled="item.count<=1">-</button>
</td>
<td>
<button @click="remove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice|getFinal}}</h2>
</div>
<div v-else>购物车为空</div>
</div>
<script src="./js/vue.js">
</script>
<script src="./js/main.js">
</script>
<script>
</script>
</body>
</html>
main.js
const app = new Vue({
el: '#app',
data: {
books: [{
id: 1,
name: '算法导论',
data: '2006-9',
price: 85.00,
count: 1
}, {
id: 2,
name: '算法导论',
data: '2006-9',
price: 85.00,
count: 1
}, {
id: 3,
name: '算法导论',
data: '2006-9',
price: 85.00,
count: 1
}, {
id: 4,
name: '算法导论',
data: '2006-9',
price: 85.00,
count: 1
}, ],
toprice: 0
},
methods: {
increment(index) {
this.books[index].count++
},
decrement(index) {
this.books[index].count--
},
remove(index) {
this.books.splice(index, 1)
}
},
filters: {
getFinal(price) {
return '$' + price.toFixed(2)
}
},
computed: {
totalPrice() {
let toprice = 0
for (let i = 0; i < this.books.length; i++) {
toprice += this.books[i].price * this.books[i].count
}
return toprice
}
}
})
运行结果