前面那篇選中默認(rèn)節(jié)點(diǎn),有朋友留言說能不能支持自定義節(jié)點(diǎn),自己想了想認(rèn)為可行,思路主要利用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: {
// 根據(jù)名稱篩選部門樹
deptName(val) {
this.$refs.tree.filter(val);
},
// 默認(rèn)點(diǎn)擊Tree第一個(gè)節(jié)點(diǎn)
deptTree(val) {
if (val) {
this.$nextTick(() => {
//this.$refs.tree.setCurrentKey('723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d');
document.querySelector(".is-current").firstChild.click();
});
}
}
},
有幾個(gè)點(diǎn)需要說明,當(dāng)開啟current-node-key
,前端生成的樹節(jié)點(diǎn)元素會(huì)帶有is-current
樣式,通過這個(gè)我們進(jìn)行判斷
注意不要使用setCurrentKey
來設(shè)置選中節(jié)點(diǎn),實(shí)測無效,原因應(yīng)該是頁面元素未加載完成,如圖:
整體思路:
后臺(tái)返回需要點(diǎn)擊的節(jié)點(diǎn)ID,需要注意的是只能是單個(gè),非數(shù)組,格式要求(string, number),通過current-node-key
綁定返回值,然后在watch中監(jiān)聽,即可完成自定義節(jié)點(diǎn)點(diǎn)擊
BUG
有朋友指出current-node-key="723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d"
在進(jìn)行動(dòng)態(tài)賦值的時(shí)候會(huì)出現(xiàn) [Vue warn]: Error in nextTick: "TypeError: Cannot read property 'firstChild' of null" 錯(cuò)誤,第一眼看到的時(shí)候我猜想肯定是current-node-key
設(shè)置出現(xiàn)問題了,經(jīng)過自己的嘗試,已解決,對(duì)原來的代碼進(jìn)行了部分修改,具體如下:
<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: {
// 根據(jù)名稱篩選部門樹
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() {
// 獲取部門樹數(shù)據(jù)
this.getTreeDept();
},
methods: {
/** 查詢部門下拉樹結(jié)構(gòu) */
getTreeDept() {
DeptAPI.treeDept().then(response => {
this.nodeKey = '723fcc371a1c54ad53d899cf2c0f8c125d3951db899665a3be43700e354ebb4d';
this.deptTree = response.treeList;
this.checkedSet = response.checkedSet;
});
},
}
以上即可實(shí)現(xiàn)自定義節(jié)點(diǎn)默認(rèn)點(diǎn)擊事件,核心在于$nextTick
的使用,Vue官網(wǎng)說明:在下次 DOM 更新循環(huán)結(jié)束之后執(zhí)行延遲回調(diào)。在修改數(shù)據(jù)之后立即使用這個(gè)方法,獲取更新后的 DOM。
感謝 @掛機(jī)打游戲