效果图:未点击时默认选中监控点
代码:
<el-tree
ref="simpleTree" //ref属性一定要有
:data="treeData" //树数据
node-key="id" //id一定要有且是唯一值
:highlight-current="true"
:expand-on-click-node="false"
:props="treeProps"
default-expand-all
@node-click="handleNodeClick" //树点击事件
></el-tree>
data中:
treeData: [],
treeId:"",
treeProps: {
id: "id",
label: "name",
children: "children"
},
methods中:
//这个事件我调接口拿到treeData的数据,是普通数据,所以我会通过下面的toTree将数据转为树形结构,若你的数据拿到本身就是树形结构 ,则忽略toTree转换那一步
getTreeData() {
setTimeout(() => {
axios({
method: "post",
url: "/api/jiekouTree"
}).then(res => {
if (res.data.code == 200) {
let arr = this.toTree(res.data.data);//这里把数据转成树形结构了
this.treeData = arr;
if (this.treeData[0].children.length === 0) {
//这一步表示若树数据中的第一条数据节点没有子节点,那就默认它的id被选中
this.treeId = this.treeData[0].id;
// this.nodeUuid = this.treeData[0].uuid;
// this.nodeName = this.treeData[0].name;
this.$nextTick(() => {
this.$refs.simpleTree.setCurrentKey(this.treeId);
});
} else {
//这一步表示 反之 若树数据中的第一条数据节点有子节点,那就默认它的子节点第一条数
//据id被选中
this.treeId = this.treeData[0].children[0].id;
//this.nodeUuid = this.treeData[0].children[0].uuid;
//this.nodeName = this.treeData[0].children[0].name;
this.$nextTick(() => {
this.$refs.simpleTree.setCurrentKey(this.treeId);
});
}
} else {
this.$message.info(res.data.msg);
}
});
}, 100);
},
// 树数据转换为树形结构
toTree(data) {
// console.log('dtaaaa',data)
if (data == []) {
return;
} else {
let cloneData = JSON.parse(JSON.stringify(data)); // 对源数据深度克隆
let tree = cloneData.filter(father => {
//循环所有项
let branchArr = cloneData.filter(child => {
return father.uuid == child.parentUuid; //返回每一项的子级数组
});
if (branchArr.length > 0) {
father.children = branchArr; //如果存在子级,则给父级添加一个children属性,并赋值
}
return father.parentUuid == "0"; //返回第一层
});
return tree; //返回树形数据
}
},
//树的点击事件,若手动点击则会切换之前默认的treeId
handleNodeClick(val, node) {
console.log("val", val, node);
if (val.children && val.children.length) {
this.$refs.simpleTree.setCurrentKey(this.treeId);
} else {
this.treeId = val.id;//这里就是自己选择的节点Id
// this.nodeUuid = val.uuid;
// this.nodeName = val.name;
this.$refs.simpleTree.setCurrentKey(this.treeId);
}
},
注意:设置默认选中必须要通过node-key中的id进行,若树数据还有其它类似id的唯一值,例如uuid,pid之类的,要使用就单独获取即可