前面那篇選中默認節點,有朋友留言說能不能支持自定義節點,自己想了想認為可行,思路主要利用el-tree 的current-node-key
和highlight-current
屬性,如圖
<el-tree
:data="deptTree"
:props="defaultProps"
:expand-on-click-node="false"
:filter-node-method="filterNode"
current-node-key="723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d"
highlight-current
node-key="id"
ref="tree"
default-expand-all
@node-click="handleNodeClick"
@node-drop="handleDrop"
draggable
>
代碼如下
watch: {
// 根據名稱篩選部門樹
deptName(val) {
this.$refs.tree.filter(val);
},
// 默認點擊Tree第一個節點
deptTree(val) {
if (val) {
this.$nextTick(() => {
//this.$refs.tree.setCurrentKey('723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d');
document.querySelector(".is-current").firstChild.click();
});
}
}
},
有幾個點需要說明,當開啟current-node-key
,前端生成的樹節點元素會帶有is-current
樣式,通過這個我們進行判斷
注意不要使用setCurrentKey
來設置選中節點,實測無效,原因應該是頁面元素未加載完成,如圖:
在這里插入圖片描述
整體思路:
后臺返回需要點擊的節點ID,需要注意的是只能是單個,非數組,格式要求(string, number),通過current-node-key
綁定返回值,然后在watch中監聽,即可完成自定義節點點擊
BUG
有朋友指出current-node-key="723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d"
在進行動態賦值的時候會出現 [Vue warn]: Error in nextTick: "TypeError: Cannot read property 'firstChild' of null" 錯誤,第一眼看到的時候我猜想肯定是current-node-key
設置出現問題了,經過自己的嘗試,已解決,對原來的代碼進行了部分修改,具體如下:
<el-tree
:data="deptTree"
:props="defaultProps"
:expand-on-click-node="false"
:filter-node-method="filterNode"
highlight-current
node-key="id"
ref="tree"
default-expand-all
@node-click="handleNodeClick"
@node-drop="handleDrop"
draggable
>
JavaScript:
watch: {
// 根據名稱篩選部門樹
deptName(val) {
this.$refs.tree.filter(val);
},
// 選中的key
nodeKey(val) {
if (val) {
this.$nextTick(() => {
this.$refs.tree.setCurrentKey(val);
this.$nextTick(() => {
document.querySelector(".is-current").firstChild.click();
});
});
}
}
},
mounted() {
// 獲取部門樹數據
this.getTreeDept();
},
methods: {
/** 查詢部門下拉樹結構 */
getTreeDept() {
DeptAPI.treeDept().then(response => {
this.nodeKey = '723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d';
this.deptTree = response.treeList;
this.checkedSet = response.checkedSet;
});
},
}
以上即可實現自定義節點默認點擊事件,核心在于$nextTick
的使用,Vue官網說明:在下次 DOM 更新循環結束之后執行延遲回調。在修改數據之后立即使用這個方法,獲取更新后的 DOM。
感謝 @掛機打游戲