Vue.js 中使用 el-tree 组件时,deptList 赋值报错:Cannot read properties of undefined (reading 'split')
在 Vue.js 中使用 el-tree 组件时,您可能遇到以下错误:Cannot read properties of undefined (reading 'split')。这个错误通常出现在您尝试使用 deptList.value = data.rows.split(',') 给 deptList 赋值时。
这个错误表明 data.rows 是 undefined,而不是一个字符串,因此无法使用 split 方法进行拆分。
问题分析
data.rows是undefined: 可能是因为查询的数据不包含rows属性,或者在后端代码中有错误,导致返回的数据没有rows属性。
解决方案
-
检查
data.rows的值: 在调用getRoleForm之前,使用console.log(data)打印data对象的值,检查data.rows是否存在以及它是否是一个字符串。 -
调整后端代码: 如果
data.rows确实是undefined,您需要确定为什么返回的数据中没有该属性。可能是因为查询的数据不包含rows属性,或者在后端代码中有错误。您需要修改后端代码,确保返回的数据包含rows属性并且它是一个字符串。 -
使用其他方法赋值: 如果无法修改后端代码,您可以尝试使用其他方法给
deptList赋值,例如使用Object.assign或spread syntax将data中的属性复制到deptList中。
示例代码
getRoleForm({ id: roleId }).then(({ data }) => {
console.log(data); // 检查 data 的值
if (data.rows) {
deptList.value = data.rows.split(','); // 如果 data.rows 存在,则进行赋值
} else {
// 处理 data.rows 不存在的情况
}
Object.assign(formData, data);
});
总结
通过检查 data.rows 的值,并根据情况调整后端代码或使用其他方法赋值,您就可以解决 Cannot read properties of undefined (reading 'split') 错误,并成功地将数据赋给 deptList。
原文地址: https://www.cveoy.top/t/topic/plyW 著作权归作者所有。请勿转载和采集!