vue elementUi tree 懶加載使用詳情

vue elementUi tree 懶加載使用詳情

背景:

vue下使用elementUIhtml

文檔:

http://element-cn.eleme.io/#/zh-CN/component/tree#tree-shu-xing-kong-jianvue

需求:

只保存二級節點中選中的數據;不保存一級節點選中的數據。node

效果:

在這裏插入圖片描述

數據來源:

後臺提供兩個接口分別用於取第一級節點和第二級節點的數據;api

思路:

點擊標籤列表時,觸發selectLabelList獲取第一級節點的數據觸發lodeNode進行填充,展開一級節點;點擊任一一級節點的下拉箭頭經過loadNode的node.level==1獲取二級節點進行填充。每次選擇都會觸發handleCheckChange獲取選中或刪除棄選的內容;最終將用戶選中的全部二級數據保存到labelCheckedList這個數組中。數組

注意點:

node-key、ref、lazy這3個屬性必定要有
 一級節點傳遞給二級節點的值是用node.data裏面的id即node.data.id而不是用官網案例上的node.id(被坑過)
  • 1
  • 2

實戰:

html:post

<el-button  @click="selectLabelList">標籤列表</el-button>
<el-tree
    node-key="id"
    ref="tree"
    highlight-current
    :props="props"
    :load="loadNode"
    lazy=""
    show-checkbox
    @check-change="handleCheckChange">
</el-tree>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

js:這是核心的部分代碼,並非全部,有的字段尚未定義。this

data() {
    return {
      labelCheckedList:[],
      props: {
          label: 'name',
          children: 'zones',
        }}
// labelCheckedList接收被勾選的數據
handleCheckChange(data){
      this.currTreeId=data.id
        setTimeout(() => {
          let currtData = this.$refs.tree.getCheckedNodes(true)
          this.labelCheckedList = currtData;
        }, 100);
    },
//懶加載時觸發
loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve(this.categorylist);
      }
      if (node.level > 1) return resolve([]);
      if(node.level === 1) { // 二級節點
        this.getChildrenNode(node,resolve)
      }
    },
// 二級節點
getChildrenNode(node,resolve) {
      let categoryId = node.data.id;
      this.$http.post('/api/getLabelListByCategoryId', {
          categoryId:categoryId
        },
        {
            emulateJSON: true,
            emulateHTTP: true
        }).then(res => {
          this.childrenList = res.body;
          if(this.childrenList.length==0){
            this.$message.error('數據拉取失敗,請刷新再試!');
            return;
          }
          resolve(this.childrenList);
        });
    },
// 收起、展現tree
selectLabelList() {
      if(!this.isShowTree){
          this.getCategorylist();
      }else{
        this.$refs.tree.$data.store.lazy = false
        this.isShowTree=false;
      }

    },
//獲取一級節點
getCategorylist(){
      this.$http.post('/api/categorylist', {
            searchInfo: this.searchLabelInfo,
          }).then(res => {
            let data = res.body.data.list;
            if(data.length > 0){
              data.forEach(item => {
                item.disabled= true;
              })
            }
            this.categorylist = data;
            this.isShowTree=true;
          })
    },
相關文章
相關標籤/搜索