本文中element-ui版本為 2.13.0
Element- UI中樹形數據table有一個屬性default-expand-all是控制樹形數據的展開和摺疊的,但是我們如果使用按鈕動態更改該屬性是沒有效果的,因為其只在table第一次初始化的時候有效。
<!-- vue頁面中table表頭設置--><el-table v-loading="listLoading" :data="list" element-loading-text="拼命加載中..." border style="width: 100%;margin-bottom: 20px;" row-key="id" highlight-current-row :show-header="showHeader" lazy :load="load" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" >
已展開項icon
未展開項icon
通過觀察頁面我們發現Element- UI中的table是通過點擊div.el-table__expand-icon元素來控制展開摺疊,展開狀態時該元素會新增一個classel-table__expand-icon--expanded。由此我們可以理一下解決思路:
一 . 點擊全部展開
獲取所有沒有class el-table__expand-icon--expanded的div.el-table__expand-icon元素,給第1步獲取到的元素添加點擊事件/*全部展開按鈕點擊方法*/ToExpandAll() { const els = document.getElementsByClassName('el-table__expand-icon') if (this.list.length !== 0 && els.length !== 0) { // 給所有的展開icon添加標記 for (let j1 = 0; j1 < els.length; j1++) { els[j1].classList.add('clickItem') } if (this.$el.getElementsByClassName('el-table__expand-icon--expanded')) { const open = this.$el.getElementsByClassName('el-table__expand-icon--expanded') // 去掉已經展開icon的標記 for (let j = 0; j < open.length; j++) { open[j].classList.remove('clickItem') } const clickItem = this.$el.getElementsByClassName('clickItem') // 給所有未展開icon添加點擊事件 for (let a = 0; a < clickItem.length; a++) { clickItem[a].click() } } } }二 . 點擊全部摺疊
獲取所有有class el-table__expand-icon--expanded的div.el-table__expand-icon元素,給第1步獲取到的元素添加點擊事件/*全部摺疊按鈕點擊方法*/ToClose() { if (this.list.length !== 0) { const elsopen = this.$el.getElementsByClassName('el-table__expand-icon--expanded') if (this.$el.getElementsByClassName('el-table__expand-icon--expanded')) { // 給所有已經展開icon添加點擊事件 for (let i = 0; i < elsopen.length; i++) { elsopen[i].click() } } } }擴展
點擊全部展開時,我們也可以移除div.el-table__expand-icon元素中的class el-table__expand-icon--expanded, 然後給所有div.el-table__expand-icon元素添加點擊事件。