最近在写vue 小demo时,遇到一些小坑,总结些与大家分享下,先上代码:
html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>购物车实例</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<div id="app" on-cloak>
<div v-if="list.length>0">
<table>
<thead>
<tr>
<th></th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tr v-for="(item,index) in list" >
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="reduce(index)" :disabled="item.count===1">-</button>
{{item.count}}
<button @click="add(index)">+</button>
</td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</table>
<!-- v-for 不能在tbody中使用 不然汇报item index未定义错误-->
<!-- <tbody> -->
<!-- </tbody> -->
<div >总价:{{totalPrice}}</div>
</div>
<div v-else>购物车不能为空</div>
</div>
<!--
<div id="app">
<ul>
<template v-for="(item,index) in list">
<li>{{index+1}}</li>
<li>{{item.name}}</li>
<li>{{item.price}}</li>
</template>
</ul>
</div> -->
</body>
<script src="../vue.js"></script>
<script src="app.js"></script>
</html>
app.js:
var app = new Vue({
el: "#app",
data: {
list: [{
id: 1,
name: 'iphone7',
price: 6188,
count: 1
}, {
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
}, {
id: 3,
name: 'MacBook pro',
price: 188888,
count: 1
}]
},
methods: {
add: function(index) {
this.list[index].count++;
},
reduce: function(index) {
if (this.list[index].count === 1) return;
this.list[index].count--;
},
remove: function(index) {
//数组中去除一个元素
this.list.splice(index, 1);
}
},
computed: {
totalPrice: function() {
var total = 0;
for (var i = 0; i < this.list.length; i++) {
var item = this.list[i];
total += item.price * item.count
}
return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
}
}
})
入坑点:
<tbody></tbody> v-for在tbody标签及子标签中无效,亲测无效
vue对象中新增一个list数组的参数:
Vue.set(app.list,3,{
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
})
删除一个元素:
list.splice(index)从数组中去除一个元素,list[index].splice(index)这个写法是错误的
替换一个元素:
app.list.splice(3,1,{
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
})