记录一个element的el-upload组件使用current-change方法的一个小坑
今天发现使用current-change点击表格时,明明有赋值,但是给别的变量赋值时竟然报TypeError Cannot create property ‘uid‘ on string
这个错误一般是 这个报错通常表示把一个不存在的属性给其赋值 这时我就很纳闷了 我打印时 明明‘id‘是存在的
组件代码的模板代码如下:
<el-table border :data="noMatchList" highlight-current-row @current-change="selectionChangeHandle" class="table-has-radio">
...
</el-table>
selectionChangeHandle(row) {
this.nomatch_id = row.id
this.selection = Object.assign({},row);
console.log(row,this.selection,"点击") //这里能正常打印出数据,页面也正常赋值了,但是还是报错
},
结果还是报上面那个错误,我这时就有点纳闷了,然后查了下文档
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
看完恍然大悟,这里是有两个参数:
currentRow:当前选中的行数据。
oldCurrentRow:上一次选中的行数据。
在 Element UI 的 el-table 组件中,当只使用一个参数时,即不传递旧的选中行数据(oldCurrentRow),会报错 TypeError: Cannot create property ‘uid’ on string。
这个错误是因为 Element UI 的表格组件内部需要为每行数据(包括当前选中行和旧的选中行数据)添加一个唯一标识符 “uid”,用于追踪和管理表格的状态。而当只传递一个参数时,Element UI 会尝试为这个参数(字符串)添加 “uid” 属性,从而导致了该错误。
要解决这个问题,可以通过在代码中进行一些调整来处理:
在 el-table 组件中添加 row-key 属性,用于指定每行数据的唯一标识符。这个标识符可以是数据项中的某个字段(如 ID),或者使用一个计算属性来生成。
在 current-change 事件处理函数中,对只有一个参数的情况进行判断,并给旧的选中行数据(oldCurrentRow)提供一个默认值,以避免报错。
代码改如下:
<template>
<el-table :data="tableData" :row-key="rowKey" @current-change="handleCurrentChange">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<!-- 其他列配置 -->
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 20 },
{ id: 2, name: '李四', age: 25 },
// 其他数据项
],
currentRow: null, // 当前选中行数据
oldCurrentRow: null // 上一次选中行数据
};
},
computed: {
rowKey() {
// 返回每行数据的唯一标识符字段,比如这里使用 id 字段作为唯一标识符
return 'id';
}
},
methods: {
handleCurrentChange(currentRow, oldCurrentRow = null) {
this.currentRow = currentRow;
this.oldCurrentRow = oldCurrentRow;
console.log('当前选中行:', currentRow);
console.log('上一次选中行:', oldCurrentRow);
}
}
};
</script>
通过添加 row-key 属性,并在 computed 中返回每行数据的唯一标识符字段(如 id),可以修复报错问题。另外,在 handleCurrentChange 方法中,给 oldCurrentRow 设置了默认值为 null,以避免只有一个参数时出现报错。
完美解决,撒花!!!
纯记录,大佬勿喷