为什么 el-table-column 绑定 key,重新赋值不更新,而 div v-for 绑定 key 会有变化。
<template>
<div class="ce-sty">
<el-table ref="tableDom1" :data="tableData.data" style="width: 100%">
<el-table-column
:prop="key"
v-for="(value, key, index) in tableData.thead"
:key="key"
:label="value.label"
>
</el-table-column>
</el-table>
<div v-for="(value, key, index) in tableData.thead" :key="key">
{{ value }}-{{ key }}-{{ index }}
</div>
<button @click="handleClick">Click</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
tableData: {
thead: {
aaa: { label: "这是aaa的头" },
bbb: { label: "这是bbb的头" },
ccc: { label: "这是ccc的头" },
},
data: [
{
aaa: "1aaa的值",
bbb: "1bbb的值",
ccc: "1ccc的值",
},
{
aaa: "2aaa的值",
bbb: "2bbb的值",
ccc: "2ccc的值",
},
{
aaa: "3aaa的值",
bbb: "3bbb的值",
ccc: "3ccc的值",
},
],
},
once: true,
};
},
methods: {
handleClick() {
this.tableData.thead = {
aaa: { label: "这是aaa的头" },
ccc: { label: "这是ccc的头" },
bbb: { label: "这是bbb的头" },
}
},
},
};
</script>
el-table-column 不绑定 key,或绑定 key 为 index:
<template>
<div class="ce-sty">
<el-table ref="tableDom1" :data="tableData.data" style="width: 100%">
<el-table-column
:prop="key"
v-for="(value, key, index) in tableData.thead"
- :key="key"
:label="value.label"
>
</el-table-column>
</el-table>
<div v-for="(value, key, index) in tableData.thead" :key="key">
{{ value }}-{{ key }}-{{ index }}
</div>
<button @click="handleClick">Click</button>
</div>
</template>
<template>
<div class="ce-sty">
<el-table ref="tableDom1" :data="tableData.data" style="width: 100%">
<el-table-column
:prop="key"
v-for="(value, key, index) in tableData.thead"
- :key="key"
+ :key="index"
:label="value.label"
>
</el-table-column>
</el-table>
<div v-for="(value, key, index) in tableData.thead" :key="key">
{{ value }}-{{ key }}-{{ index }}
</div>
<button @click="handleClick">Click</button>
</div>
</template>
对 tableData.thead 重新赋值都会刷新:
因为key值不能存在相同的问题,在第一种方式中el-table-column与div中存在3个key值相同的dom节点,在tableData对象中数据改变时,两个key值相同的dom节点只会重新渲染其中一个dom节点,所以只会改变div中的数据;在第二种方式中两个v-for的key值都不相同了,所以可以正常重新渲染。但是不建议使用index作为key。