Vue使用v-for显示列表时,数组里的item数据更新,视图中
2019-10-12 本文已影响0人
手指乐
- 由于初始化类型错误导致的不更新,代码是这样的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app-7">
<div @click="update()">update</div>
<ol>
<li v-for="item in groceryList" v-bind:key="item.id">
{{item.text}}
</li>
</ol>
</div>
</body>
<script type="text/javascript">
var app7 = new Vue({
el: '#app-7',
data: {
groceryList: []
},
methods: {
update: function() {
this.groceryList[0].text = "newvalue"
}
},
created: function() {
let adddata = [];
adddata.id = 0;
adddata.text = "test";
this.groceryList.push(adddata);
}
});
</script>
</html>
使用索引直接更新数组中的项目,比如:
this.groceryList[0].text = "newvalue"
发现视图中的项目并不会更新
问题出在 let adddata = []; 写错了,让adddata是一个数组类型了,vue在监听数据更新的时候,判断是数组类型,并不会对它的属性的变更做处理,而只会对数组里元素的改变做处理,把 let adddata = []; 改成 let adddata = {};即可
或这样也可以:
let adddata = {
id: 0,
text: "test"
};
this.groceryList.push(adddata);
- vue不能检测到数组元素的直接赋值,比如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app-7">
<div @click="update()">update</div>
<ol>
<li v-for="item in groceryList" v-bind:key="item.id">
{{item.text}}
</li>
</ol>
</div>
</body>
<script type="text/javascript">
var app7 = new Vue({
el: '#app-7',
data: {
groceryList: []
},
methods: {
update: function() {
this.groceryList[0] = {
id: 0,
text: "newvalue"
};
}
},
created: function() {
let adddata = {
id: 0,
text: "test"
};
this.groceryList.push(adddata);
}
});
</script>
</html>
this.groceryList[0] = {
id: 0,
text: "newvalue"
};
}
vue不能检测这种改变,只能检测到push,pop等元素出入栈的操作
可以改成这样,把旧元素替换成新元素(旧元素出栈,新元素入栈)
update: function() {
this.groceryList.splice(0, 1, {
id: 0,
text: "newvalue"
});
}
},
即使groceryList是一个普通的非对象数组,也需要这样才能同步更新视图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
<div id="app-7">
<div @click="update()">update</div>
<ol>
<li v-for="item in groceryList" v-bind:key="item.id">
{{item}}
</li>
</ol>
</div>
</body>
<script type="text/javascript">
var app7 = new Vue({
el: '#app-7',
data: {
groceryList: []
},
methods: {
update: function() {
//this.groceryList[0] = "newvalue";//不行
this.groceryList.splice(0, 1, "newvalue");
}
},
created: function() {
let adddata = "test";
this.groceryList.push(adddata);
}
});
</script>
</html>