网上下了一个关于vue2-org-tree
组件的demo,可以正常跑起来,但是把代码组件页面原本搬到项目中,怎么也跑不起来,确认了vue版本都是2.6.11
,但是一直报错,错误信息如下:
`
OrgTree.vue 代码如下:
<template>
<div class="org-tree">
<vue2-org-tree
:horizontal="false"
:data="data"
collapsable
:render-content="renderContent"
:label-class-name="labelClassName"
@on-expand="onExpand"
/>
</div>
</template>
<script>
export default {
name: "OrgTree",
data() {
return {
data: {},
labelClassName: "bg-color-blue",
};
},
created() {},
methods: {
collapse(list) {
list.forEach(child => {
if (child.expand) {
child.expand = false;
}
child.children && this.collapse(child.children);
});
},
onExpand(e, data) {
console.log(data, "data");
if ("expand" in data) {
data.expand = !data.expand;
if (!data.expand && data.children) {
this.collapse(data.children);
}
} else {
this.$set(data, "expand", true);
}
},
toggleExpand(data, val) {
if (Array.isArray(data)) {
data.forEach(item => {
this.$set(item, "expand", val);
if (item.children) {
this.toggleExpand(item.children, val);
}
});
} else {
this.$set(data, "expand", val);
if (data.children) {
this.toggleExpand(data.children, val);
}
}
},
renderContent(h, data) {
return <div class="treeItem">1--{data.label}</div>;
},
},
mounted() {
this.data = {
label: "江苏XX",
value: "-1",
children: [
{
value: "reqjfxqfzr",
label: "需求室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
{
value: "req_fzr_kf",
label: "开发室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
{
value: "req_fzr_dsj",
label: "大数据室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
{
value: "req_fzr_bas",
label: "经分室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
{
value: "reqownerinfo",
label: "信息化室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
{
value: "reqownerinfo-aq",
label: "安全室负责人",
children: [
{
label: "任通",
value: "1000035939",
},
{
label: "林萍",
value: "23000068",
},
{
label: "王庆安",
value: "23000079",
},
],
},
],
};
this.toggleExpand(this.data, true);
},
};
</script>
<style lang="scss">
.bg-color-blue {
color: #ffffff;
background-color: skyblue;
}
</style>
根据错误信息和你的代码,问题出在尝试读取 children 属性时,该属性未定义。以下是修复代码的建议:
这样可以确保每个节点都有
children
属性,避免TypeError: Cannot read properties of undefined (reading 'children')
错误。