filters
过滤器
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)//保留2位小数
}
}
index.html ```html <!DOCTYPE html>
书籍名称 出版日期 价格 购买数量 操作 {{item.id}} {{item.name}} {{item.date}} {{item.price | showPrice}} {{item.count}} 总价格: {{totalPrice | showPrice}}
购物车为空
- main.js
```javascript
const app = new Vue({
el: '#app',
data: {
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
},
]
},
methods: {
// getFinalPrice(price) {
// return '¥' + price.toFixed(2)
// }
increment(index) {
this.books[index].count++
},
decrement(index) {
this.books[index].count--
},
removeHandle(index) {
this.books.splice(index, 1)
}
},
computed: {
totalPrice() {
let totalPrice = 0
for (let i = 0; i < this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count
}
return totalPrice
// for (let i in/of this.books)
// reduce
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
- style.css ```css table { border: 1px solid #e9e9e9; border-collapse: collapse; border-spacing: 0; }
th, td { padding: 8px 16px; border: 1px solid #e9e9e9; text-align: left; }
th { background-color: #f7f7f7; color: #5c6b77; font-weight: 600; } ```