<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>vue购物车案例</title>
</head>
<style>
table {
width: 1000px;
margin: 200px auto;
}
th,td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
</style>
<body>
<div id="app">
<table>
<thead>
<tr>
<th>书籍名称</th>
<th>日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books" :key="index">
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{getFinalPrice(item.price)}}</td>
<td>
<button @click="jian(index)">-</button>
{{item.count}}
<button @click="add(index)">+</button>
</td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2 style="text-align:center">总价格:{{totalPrice}}</h2>
</div>
</body>
<script>
const app = new Vue({
el:'#app',
data:{
books:[
{
id:1,
name:"算法导论",
date:"2006-9",
price:350.00,
count:1,
},
{
id:2,
name:"数据结构",
date:"2007-9",
price:185.00,
count:1,
},
{
id:3,
name:"软件测试",
date:"2008-9",
price:300.00,
count:1,
},
{
id:4,
name:"软件需求",
date:"2009-9",
price:90.00,
count:1,
},
{
id:5,
name:"Android",
date:"2010-9",
price:150.00,
count:1,
},
{
id:6,
name:"Java",
date:"2011-9",
price:240.00,
count:1,
},
]
},
methods:{
getFinalPrice(price) {
// 返回价格并且保留小数后两位
return '¥' + price.toFixed(2)
},
add(index){
this.books[index].count++;
},
jian(index){
this.books[index].count--;
this.books[index].count = this.books[index].count<=0?0:this.books[index].count;
},
remove(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;
}
},
})
</script>
</html>
vue购物车及计算属性computed的基本使用
于 2021-05-24 10:28:40 首次发布