7-VUE基础项目练习(购物车)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./js/vue.min.js"></script>
<title></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.day}}</td>
<td>{{item.pay |getpay }}</td><!-- 使用过滤器 -->
<td>
<button @click="jian(index)" :disabled="item.number<=1">-</button>
{{item.number}}
<button @click="jia(index)">+</button>
</td>
<td><button @click="remo(index)">移除</button></td>
</tr>
</tbody>
</table>
<div>总价格为:{{totalprice |getpay}}</div>
</div>
<h2 v-else>购物车为空</h2>
</div>
<script>
const app = new Vue({
el:"#app",
data(){
return{
books:[
{
id:1,
name:'《算法导论》',
day:'2006-9',
pay:85.00,
number:1
},
{
id:2,
name:'《UNIX编程艺术》',
day:'2006-2',
pay:59.00,
number:1
},
{
id:3,
name:'《编程珠玑》',
day:'2008-10',
pay:39.00,
number:1
},
{
id:4,
name:'《代码大全》',
day:'2006-3',
pay:128.00,
number:1
}
]
}
}
,
computed:{
totalprice(){
let a = 0
for(let i =0 ;i<this.books.length;i++){
a += this.books[i].pay * this.books[i].number
}
return a
}
},
methods:{
jia(index){
this.books[index].number++
console.log('+',index)
},
jian(index){
this.books[index].number--
console.log('-',index)
},
remo(index){
this.books.splice(index,1)
}
},
filters:{
getpay(pay){
return '¥'+pay.toFixed(2)
}/*过滤器*/
}
})
</script>
</body>
</html>