场景: 在使用 element 表格时(el-table),有一列为“操作”列,用以动态显示不同按钮,通过插槽获取数据值来判断。
错误: 由于添加的按钮较多,使用的 v-if 较多,当进行条件筛选重新赋值列表时发生了错误,如下:
Error in nextTick: “NotFoundError: Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node.”
原因: el-table 传入数据后,将循环渲染行,所以会生成多个相同的操作按钮,当我们通过 v-if 进行DOM元素更新时,vue 会分不清这些 DOM,最终造成渲染失败。
当时很苦恼,因为这种报错真的很少见,通过搜集各种相关问题,最终得出一下解决方案。
解决示例:
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" type="text">查看el-button>
<el-button
size="mini"
type="text"
:key="'xg' + scope.row.id"
v-if="scope.row.status === '20'"
>修改
el-button>
<el-button
size="mini"
type="text"
:key="'yq' + scope.row.id"
v-if="scope.row.status === '40'"
>延期
el-button>
<el-button
size="mini"
type="text"
:key="'sc' + scope.row.id"
>删除
el-button>
<el-button
size="mini"
type="text"
:key="'bhyy' + scope.row.id"
v-if="scope.row.status === '50'"
>驳回原因
el-button>
<el-button
size="mini"
type="text"
:key="'txjl' + scope.row.id"
v-if="scope.row.status === '40'"
>通行记录
el-button>
template>
el-table-column>
还有一种更好的办法,嵌套一层 div 标签,给标签添加key值:
<el-table-column label="操作">
<template slot-scope="scope">
<div :key="'cz' + scope.row.id + new Date().getTime()">
<el-button size="mini" type="text">查看el-button>
<el-button
size="mini"
type="text"
v-if="scope.row.status === '20'"
>修改
el-button>
<el-button
size="mini"
type="text"
v-if="scope.row.status === '40'"
>延期
el-button>
<el-button
size="mini"
type="text"
>删除
el-button>
<el-button
size="mini"
type="text"
v-if="scope.row.status === '50'"
>驳回原因
el-button>
<el-button
size="mini"
type="text"
v-if="scope.row.status === '40'"
>通行记录
el-button>
div>
template>
el-table-column>