vue的基础知识
购物车案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-if="books.length>=1">
<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>{{getFullprice(book.price)}}</td>-->
<td>{{book.price | showPrice}}</td>
<td>
<button @click="incremcount(index)" :disabled="book.count<1">-</button>
{{book.count}}
<button @click="addcount(index)" :disabled="book.count>=10">+</button>
</td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 1, name: '回到明朝当王爷', date: '2010-02-25', price: 23, count: 1},
{id: 2, name: '红楼梦', date: '1546-02-09', price: 25, count: 1},
{id: 3, name: '三国演义', date: '1365-05-15', price: 87, count: 1},
{id: 4, name: '石头记', date: '1995-02-1', price: 16, count: 1},
{id: 5, name: '钢铁怎么炼成的', date: '2041-02-25', price: 43, count: 1},
]
},
methods: {
incremcount(i){
if (this.books[i].count >0){
this.books[i].count --
} else {
alert('不能再少了!')
}
},
addcount(i) {
if (this.books[i].count <=9){
this.books[i].count ++
} else {
alert('没有库存了!')
}
},
remove(i) {
this.books.splice(i,1)
},
getFullprice(price) {
return '¥' + price.toFixed(2)
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
},
computed: {
totalPrice() {
let result = 0;
for (let i in this.books) {
result += this.books[i].price*this.books[i].count
}
return result
}
}
})
</script>
</body>
</html>