1. 程式人生 > 程式設計 >vue el-tree 預設展開第一個節點的實現程式碼

vue el-tree 預設展開第一個節點的實現程式碼

vue 的樹形控制元件 el-tree 可以用來方便地實現樹形控制元件,但是官方文件中,關於控制元件的預設展開只有預設展開全部或者預設全部關閉,如下所示:

在這裡插入圖片描述

對於指定節點的展開,需要指定其id,從而通過 default-expanded-keys 設定預設展開的節點。
對於後臺返回的資料,預設展開其第一層的第一個,其實很簡單:對於獲取到的後臺資料,將其第一層節點新增到陣列中,將 default-expanded-keys 繫結陣列,從而設定預設展開的節點。
實際應用:預設展開第一層節點中的第一個節點:

<template>
 <section>
  <!-- 機構型別編碼表 -->
  <el-row class="toolbar" style="width: 20%;height:600px" align="left">
   <div class='treeClass'>
    <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"
     highlight-current node-key="id" :default-expanded-keys="treeExpandData">
    </el-tree>
   </div>
  </el-row>
 </section>
</template>
<script>
export default {
  data() {
   return {
    treeData:[],//後臺返回的tree樹列表
    treeExpandData:[],//自己定義的用於接收tree樹id的陣列
    provincialCenterId:'',defaultProps: {
     children: 'item',label: 'name',},}
  },created(){
   this.getEquipmentList()
  },methods: {
   // 獲取樹形結構預設展開節點
   getRoleTreeRootNode(provincialCenterId) {
    this.treeExpandData.push(provincialCenterId)   
    },//獲取tree樹列表
   getEquipmentList: function(params){
    this.listLoading = true
    this.$api.ckApi.treeList({typeTag:true}).then((res)=>{
     if(res.code==200){
      this.treeData = res.resultDownload;
      this.provincialCenterId = this.treeData[0].id //預設展開第一個節點
      this.getRoleTreeRootNode(this.provincialCenterId)
      this.listLoading = false
     }else{
      this.$message.error(res)
     }
    })
   },}
</script>

效果圖:

在這裡插入圖片描述

總結

到此這篇關於vue el-tree 預設展開第一個節點的實現程式碼的文章就介紹到這了,更多相關vue el-tree預設展開節點內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!