Vue.js 中 'TypeError: Cannot read properties of undefined (reading 'row')' 错误解决方法
Vue.js 中 'TypeError: Cannot read properties of undefined (reading 'row')' 错误解决方法
在使用 Vue.js 开发项目时,经常会遇到各种错误。其中,'TypeError: Cannot read properties of undefined (reading 'row')' 错误是比较常见的一种,尤其是在使用 el-dropdown 组件时。
错误原因
这个错误通常发生在 handleCommand2 函数中,当调用 handleDelete 函数时,row 参数为 undefined,导致 row.personId 读取属性失败。
解决方法
-
检查数据来源: 确认
row参数是否正确传递给handleCommand2函数。在el-dropdown组件的@command事件中,scope.row应该包含当前行的数据。 -
处理
undefined: 使用条件判断或可选链操作符来处理row为undefined的情况。
代码示例
// 修改后的 handleCommand2 函数
handleCommand2(command, row) {
switch (command) {
case 'handleDelete':
if (row) { // 判断 row 是否存在
this.handleDelete(row);
}
break;
case 'clearData':
this.clearData();
break;
default:
break;
}
},
// 修改后的 handleDelete 函数
handleDelete(row) {
console.log(row, 'rowwww');
const personIds = row?.personId || this.ids; // 使用可选链操作符
this.$confirm(
'是否确认删除综合所得申报-稿酬所得编号为' + personIds + '的数据项?',
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(function () {
return delReportingRoyaltiesIncome(personIds);
})
.then(() => {
this.getList();
this.msgSuccess('删除成功');
})
.catch(() => {});
},
// 完整代码(仅示例):
<template>
<div>
<el-table :data="tableData">
<el-table-column prop="personId" label="人员ID" />
<el-table-column label="操作" width="150">
<template slot-scope="scope">
<el-button type="primary" plain size="mini">
<el-dropdown trigger="click" @command="(command) => handleCommand2(command, scope.row)">
<span class="el-dropdown-link">
更多操作<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="handleDelete">删除</el-dropdown-item>
<el-dropdown-item command="clearData">数据清除</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
ids: '',
};
},
methods: {
handleCommand2, // ...
handleDelete, // ...
getList, // 获取表格数据方法
msgSuccess, // 成功提示方法
delReportingRoyaltiesIncome, // 删除数据方法
},
};
</script>
总结
通过检查数据来源和处理 undefined 情况,可以有效解决 'TypeError: Cannot read properties of undefined (reading 'row')' 错误。建议在代码中尽量使用条件判断或可选链操作符来处理可能为 undefined 的值,提高代码的健壮性。
原文地址: https://www.cveoy.top/t/topic/bpG7 著作权归作者所有。请勿转载和采集!