1. 程式人生 > >[Vue.js — iView — Tree] 點選樹元件父節點名稱時展開、收縮後代節點

[Vue.js — iView — Tree] 點選樹元件父節點名稱時展開、收縮後代節點

適用於iview tree。

```
<Tree ref="tree" :data="data" :load-data="loadData" @on-select-change="selectChange" show-checkbox/>
```


```
data() {
  return {
    data: [],
    id: 0
  }
},
methods: {
  loadData (item, callback) {
    this._loadData(item.id, callback)
  },
  _loadData (code, callback) {
    this.$http.get('/service-cutover/datasets/complaints/types?pcode=' + code).then((response) => {
      const array = []
      for (let i = 0; i < response.data.length; i++) {
        let item = response.data[i]
        array.push(item = {id: item.code, title: item.name, loading: false, children: [], source: item})
        if (item.source.leaf) delete item.loading
      }
      callback(array)
    })
  },
  selectChange (selectedList) {
    const node = selectedList[selectedList.length - 1] // 獲取當前點選的節點
    if (node) {
      this._loadData(node.id, (response) => {
        if (!response) return        // 沒有子節點則返回
        let array = []
        response.forEach((item) => { // 遍歷子節點,然後在各子節點上遞迴呼叫請求下一層後代
          array.push(item)
          this._loadData(item.id, () => {})
        })
        node.children = array // 掛載子節點
        node.expand = true    // 展開子節點樹
      })
    }
  }
},
mounted () {
  this._loadData(this.id, (array) => { // 後端邏輯是獲取父節點id,返回直接後代列表
    this.data = array
  })
}
```