问题描述:为了每次更改后看起来更加友好,保存上次操作完项来默认展开,因此添加了default-expanded-keys属性。添加之后发现,默认展开的项通过控制node 无法实现关闭,只能点前面的icon 来关闭。
思路:在网上看别人使用auto-expand-parent来控制是否默认打开,发现并不能实现。后面发现在接口调用后手动清除default-expanded-keys可以恢复。
解决方法:default-expanded-keys只在调取接口时设置,在调取完之后手动清除
代码:
getData(isOpenAtricle = false) {
this.directoryList().then(res => {
this.handleData(res)
this.treeList = res
//此处从点击过的节点中获取默认展开
if (!_.isEmpty(this.currentTree)) this.defaultActiveId = this.currentTree.id
this.$nextTick(() => {
//设置选中状态并清空默认展开的值
this.$refs.helpTree.setCurrentNode(this.defaultActiveId)
this.defaultActiveId = ''
})
})
},
// 用于处理树形数据
handleData(data, level = 1) {
// 遍历数组
for (let item of data) {
item.level = level
!item.title && (item.title = item.directoryName)
if (Array.isArray(item.childDirectories) && item.childDirectories.length > 0) {
item.children = item.childDirectories // 重命名键名
delete item.childDirectories // 删除旧键名
this.handleData(item.children, 2)
}
if (Array.isArray(item.articles) && item.articles.length > 0) {
item.children = item.articles // 重命名键名
delete item.articles // 删除旧键名
item.children.forEach(article => {
article.level = 3
// 初始时设置默认的节点
if (_.isEmpty(this.currentTree)) this.currentTree = article
})
}
}
},
后续问题记录:后面看了一些其他博客,发现点击icon可以展开,而点击使用自定义slot无法展开是因为,直接操作插槽提供的node导致,需要使用element提供的node-click事件提供的node来操控。
handleNodeClick(data, node,_this){
node.expanded = !node.expanded
}