設置默認展開
將default-expanded-keys
的值設為想展開的node-key
值對應的數組即可,此處的choiceId設置為常量1,展開的是id為1的節點
<el-tree ref="tree"
:data="treeData"
highlight-current
node-key="id"
:props="defaultProps"
:default-expanded-keys="[1]"
:filter-node-method="filterNode">
</el-tree>
設置為默認選中轉態
設置默認展開后你會驚奇的發現,這沒人性的設計居然沒有設置選中狀態!!!驚喜不驚喜,意外不意外!!不過沒關系,見招拆招,此時需要使用方法setCurrentKey
進行設置,若發現此法報錯則需加入$nextTick()
解決,
此處將展開默認id為1的對象
如下
this.$nextTick(() => {
this.$refs.tree.setCurrentKey(1)
})
設置選中狀態的css樣式
el-tree默認的顯示狀態是不明顯的,給它加上css樣式即可顯示出想要的效果,
未加樣式的效果
加了樣式的效果
注意
:此法el-tree需要加上 highlight-current屬性
代碼:
/deep/.el-tree--highlight-current
.el-tree-node.is-current
> .el-tree-node__content {
background-color: #409eff;
color: white;
}
設置編輯后默認展開與選中
如下當用戶對樹的數據進行增刪改時,此處選擇的方案是重新像后台請求回來數據進行刷新,此時init(初始化)函數應當可以繼續使用
點擊節點后需要將節點的值保留下來,在修改好節點之后就不會丟失該節點
<el-tree ref="tree"
:data="treeData"
highlight-current
node-key="id"
:props="defaultProps"
:default-expanded-keys="[choiceId]"
:filter-node-method="filterNode"
@node-click="(data)=>{choiceId = data.id}"
>
</el-tree>
此處init設置如下:
async init () {
//獲取后台返回的數據
let resData = (await sqConfigTreeSearch()).data
//遞歸構造樹形數據
function makeTree (pid) {
const temp = []
for (let i = 0; i < resData.length; i++) {
if (resData[i].pid === pid) {
//由於后台返回的字段沒有label,此處需要另行添加
resData[i].label = resData[i].name
temp.push(resData[i])
resData[i].children = makeTree(resData[i].id)
}
}
return temp
}
this.treeData = makeTree(null)
//第一次的choiceId設置為第一個數據,若之后設置了選中則無需更改
this.choiceId === '' && (this.choiceId = this.treeData[0].id)
//設置選中
this.$nextTick(() => {
this.$refs.tree.setCurrentKey(this.choiceId)
})
},