vue-demo.html
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" type="text/css" href="vue-css-demo.css" />
<body>
<div id="app">
<table>
<thead>
<tr>
<th>ID</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.price | showPrice }}</td>
<td>
<button v-bind:disabled="item.num <=1" v-on:click="decrement(index)">-</button>
{{item.num}}
<button v-on:click="increment(index)">+</button>
</td>
<td><button v-on:click="removeOne(index)">delete</button></td>
</tr>
</tbody>
</table>
<div>总价:{{getTotal}}</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="vue-js-demo.js"></script>
</html>
vue-js-demo.js
const app = new Vue({
el:"#app",
data:{
//存入数据
books:[
{
id:1,
name:"计算机网络",
price: 10,
num:0
},
{
id:2,
name:"J2EE",
price: 11,
num:0
},
{
id:3,
name:"计算机组成原理",
price: 12,
num:0
},
{
id:4,
name:"计算机基础",
price: 13,
num:0
}
],
},
methods:{
increment(index){
this.books[index].num++
},
decrement(index){
this.books[index].num--
},
//删除:splice(start,count) 从哪里开始,删除多少个数 splice可用于删除,修改,新增
removeOne(index){
this.books.splice(index,1);
}
},
computed: {
getTotal(){
let all = 0;
for(var i=0;i<this.books.length;i++){
all+=this.books[i].price*this.books[i].num;
}
return all;
}
},
//过滤器:返回特定格式的数据展示
filters:{
showPrice(price){
return '¥'+price.toFixed(2)
}
}
})
效果: