问题演示
首先,使用定时器演示从后台获取过来数据,然后添加isPlaying字段,表格能正常渲染出来。
但是当我们点击修改按钮修改isPlaying的时候,isPlaying的实际数据已经改变但是表格渲染出来的值却没变。
<template>
<div>
<el-table :data="list" style="width: 100%">
<el-table-column label="日期" width="180">
<template slot-scope="scope">
<span>{{ scope.row.value }}</span>
</template>
</el-table-column>
<el-table-column prop="text" label="姓名" width="180">
<template slot-scope="scope">
<span>{{ scope.row.text }}</span>
</template>
</el-table-column>
<el-table-column prop="address" label="地址">
<template slot-scope="scope">
<span>{{ scope.row.isPlaying }}</span>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handle(scope)">修改</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
};
},
created() {
this.getTableData();
},
watch: {
checkedList: {
deep: true,
handler(val) {
console.log(val);
}
}
},
methods: {
handle(scope) {
scope.row.isPlaying = false;
},
getTableData() {
setTimeout(() => {
this.list = [
{
value: 0,
text: 'aaa'
},
{
value: 1,
text: 'bbb'
},
{
value: 2,
text: 'nnn'
}
];
this.list.forEach(item => {
item.isPlaying = true;
});
});
}
}
};
</script>
原因分析,首先我们获取过来数据后直接赋值给list,获取到list后表格会直接进行渲染操作,此时双向绑定的只是value和text两个字段,isPlaying并没有进行双向绑定上,所以第一个解决方案就是添加isPlaying这个字段的时候不要直接进行添加,可以使用官方提供的this.$set(this.list,‘isPlaying’,true)这种方式进行添加,这样可以是添加上去的数据进行双向绑定。
第二种方式也是主要介绍的一种方式,首先从后台拿到数据后,先不要赋值给要渲染的list中,可以先定义一个中间变量接收,然后在通过中间变量进行添加字段,添加完字段以后在进行表格的渲染。
方式如下:
首先定义一个arr数组,通过arr接收数据,接收完在添加字段,最终将添加好的数据给到list这样所有数据就能够双向绑定上,页面也会随着数据变化而变化
<template>
<div>
<el-table :data="list" style="width: 100%">
<el-table-column label="日期" width="180">
<template slot-scope="scope">
<span>{{ scope.row.value }}</span>
</template>
</el-table-column>
<el-table-column prop="text" label="姓名" width="180">
<template slot-scope="scope">
<span>{{ scope.row.text }}</span>
</template>
</el-table-column>
<el-table-column prop="address" label="地址">
<template slot-scope="scope">
<span>{{ scope.row.isPlaying }}</span>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handle(scope)">添加</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
list: []
};
},
created() {
this.getTableData();
},
watch: {
checkedList: {
deep: true,
handler(val) {
console.log(val);
}
}
},
methods: {
handle(scope) {
scope.row.isPlaying = false;
},
getTableData() {
let arr = [];
setTimeout(() => {
arr = [
{
value: 0,
text: 'aaa'
},
{
value: 1,
text: 'bbb'
},
{
value: 2,
text: 'nnn'
}
];
arr.forEach(item => {
item.isPlaying = true;
});
this.list = arr;
});
}
}
};
</script>