1、需求描述:点击按钮切换树形的章节,同时高亮
2、代码实现
1)style样式添加
<style>
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
background-color: #81d3f8 !important; //高亮颜色
color:#fff; // 字体颜色
}
</style>```
2)组件添加
```javascript
<el-tree
ref="treeRef"
:data="treeData"
node-key="key" //node-key必须要绑定唯一id,我这里的id是key所以使用key
:highlight-current="true" //设置高亮
:default-expanded-keys="['0-1-0']" // 默认展开
@node-click="handleNodeClick" // 节点点击事件
></el-tree>
3)事件
mounted(){
this.$refs.treeRef.setCurrentKey(this.treeData[0].key); //threeData是树形结构的数据
//toNextClick是“下一步”按钮触发的事件
this.$bus.$on("toNextClick", () => {
this.getkey(this.treeData, this.componentsKey); //this.componentsKey是当前的key
//找到点击下一步之后的key值
this.$refs.treeRef.setCurrentKey(this.keys); //添加高亮
});
}
注:其他函数代码
// 寻找下一个key的位置
getkey(obj, okey) {
//找到okey在的位置
let treeDataLen = this.treeData.length;
let rootKey;
let parentKey;
let parentArrLen;
let parentArr;
let rootArr = this.treeData;
if (!okey) {
okey = "0-0";
}
let num = okey.match(/-/gim).length;
if (num == 2) {
//二级菜单
rootKey = okey.slice(0, 3);
parentKey = rootKey;
} else if (num == 3) {
rootKey = okey.slice(0, 5);
parentKey = okey.slice(0, 3);
} else {
//直接去下一个
rootKey = okey;
parentKey = rootKey;
}
let rootindex = rootArr.map(item => item.key).indexOf(rootKey);
//找到okey的上一级的children长度
let parentObj = this.treeData.find(item => {
return item.key == parentKey;
});
if (parentObj.key == "0-0") {
if (rootindex + 1 < treeDataLen && rootArr[rootindex + 1].children) {
this.str = rootArr[rootindex + 1].children[0].key;
}
return;
} else {
parentArr = parentObj.children ? parentObj.children : [];
}
//找到okey的下标
parentArrLen = parentArr.length;
let keyindex = parentArr.map(item => item.key).indexOf(okey);
//根元素的下标
if (keyindex + 1 > parentArrLen - 1 && rootindex + 1 >= treeDataLen) {
this.str = okey;
} else if (
keyindex + 1 > parentArrLen - 1 &&
rootindex + 1 < treeDataLen
) {
//子元素超出但是根还有
if (rootArr[rootindex + 1].children) {
this.str = rootArr[rootindex + 1].children[0].key;
}
} else {
this.str = parentArr[keyindex + 1].key;
}
}
}```