坑:Vue 动态添加的数据属性,双向绑定渲染异常

更新日期: 2018-09-06 阅读次数: 11952 分类: VueJS

代码示例,使用 element ui 的 el-table, 将返回的数据列表,逐行渲染到 table row 上,每行可以编辑 staffs 字段,即用 el-select v-model 绑定了 staffs 字段。

<template slot-scope="scope">
   <el-select v-model="scope.row.staffs" multiple
...

问题的现象是,数据在初始化之后,可以正确的渲染到视图上,但是后续修改的内容没有同步渲染到视图上。

有问题的代码。

var that = this;

$.ajax({
	method: "GET",
	url: "get_all_sites",
}).done(function( msg ) {
	that.sites = msg.data;

	for (var i = 0, len = that.sites.length; i < len; i++) {
		if (SOME_LOGIC)
			that.sites[i]['staffs'] = [1, 2];
		} else {
			that.sites[i]['staffs'] = [];
		}
	}
});

后来查到,如果在数据实例创建之后添加新的属性到数据实例上,它不会触发视图更新。。。

所以,解决方案就是,初始化时,就将新属性默认添加上,不要初始化之后再动态添加新属性。

var that = this;

$.ajax({
	method: "GET",
	url: "get_all_sites",
}).done(function( msg ) {
	sites = msg.data;

	for (var i = 0, len = sites.length; i < len; i++) {
		if (SOME_LOGIC)
			sites[i]['staffs'] = [1, 2];
		} else {
			sites[i]['staffs'] = [];
		}
	}

	that.sites = sites;
});

修改之后一切正常了。

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式