el-tree加載完成后默認觸發點擊事件非默認選中(下)支持自定義節點


前面那篇選中默認節點,有朋友留言說能不能支持自定義節點,自己想了想認為可行,思路主要利用el-tree 的current-node-keyhighlight-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。

感謝 @掛機打游戲

資料:
Vue-nextTick
vue源碼解析:nextTick


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM