解决解决Vue不能检测数组或对象变动的问题不能检测数组或对象变动的问题
来看一个实例:来看一个实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script>
<style>
li:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div class="wrap">
<ul>
<li v-for="item,index in items" v-on:click="handle(index)">
<span>{{item.name}}</span>
<span>{{numbers[index]}}</span>
</li>
</ul>
</div>
<script>
var vm = new Vue({
el: ".wrap",
data: {
numbers: [],
items: [
{name: 'jjj'},
{name: 'kkk'},
{name: 'lll'},
] },
methods: {
handle: function (index) {
// WHY: 更新数据,view层未渲染,但通过console这个数组可以发现数据确实更新了
if (typeof(this.numbers[index]) === "undefined" ) {
// 注:下面这么设置是可以的。例如
// var arr = [];
// arr[3]=3;
// console.log(arr) //[empty × 3, 3] this.numbers[index] = 1;
// this.numbers.splice(index,0,1) //用splice方法能同步显示,但得不到想要的效果
} else {
this.numbers[index]++;
// this.numbers.splice(index,1,this.numbers[index]++)
}
// console.log(this.numbers)
}
}
});
</script>
</body>
</html>
想实现的效果是点击 li 看 vm.nymbers[index] 是否存在,不存在设置为1,存在的话加1。
点击之后数字并没有在view层更新,而通过console打印发现数据更新了,只是view层没有及时的检测到。
再看一个改动之后的:再看一个改动之后的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue</title>
<script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script>
<style>
li:hover {
cursor: pointer;
}
</style>
</head>
<body>