话不多说 先看效果
当数量为1时 不可以在减
点击删除 即删除该本书
上代码
写代码之前 要引入vue.js
<!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">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table border="1px solid">
<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.date}}</td>
<td>{{item.price | showP}}</td>
<td>
<button @click="incr(index)">+</button>
{{item.num}}
<button @click="decr(index)" v-bind:disabled="item.num<=1">-</button>
</td>
<td>
<button @click="removesh(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{{total|showP}}</h2>
</div>
<h2 v-else="">购物车为空</h2>
</div>
<script src="vue.js"></script>
<script src="main.js"></script>
</body>
</html>
在外部写了main.js
const app = new Vue({
el: "#app",
data:{
books:[
{
id:1,
name:"西游记",
date:"2021-02",
price:"39.00",
num:1
},
{
id:2,
name:"水浒传",
date:"2019-02",
price:"29.00",
num:1
},
{
id:3,
name:"红楼梦",
date:"2016-02",
price:"26.00",
num:1
},
{
id:4,
name:"三国演义",
date:"2009-02",
price:"28.00",
num:1
}
]
},
methods: {
incr(index){
this.books[index].num++
},
decr(index){
this.books[index].num--
},
removesh(index){
this.books.splice (index,1)
}
},
computed: {
// 直接当做普通属性调用不加括号
// 任何data中数据变化立即重新计算
// 计算属性会缓存
total(){
let result=0
// for (let i = 0; i < this.books.length; i++) {
// result=result+this.books[i].price*this.books[i].num
// }
// return result;
for(let item of this.books){
result=result+item.price*item.num
}
return result;
}
},
filters:{
showP(price){
return '¥' + parseInt(price).toFixed(2)
}
}
})