vue-treeselect 的使用

纵然是瞬间 提交于 2020-08-07 06:43:57

1、安装 

npm install --save @riophae/vue-treeselect

然后在页面中引入

  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

注册组件

components: { Treeselect }

使用

<treeselect v-model="value" :multiple="true" :options="options" />

完整代码

<template>
  <div id="app">
    <treeselect v-model="value" :multiple="true" :options="options" />
  </div>
</template>

<script>
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    // register the component
    components: { Treeselect },
    data() {
      return {
        // define the default value
        value: null, // 不能写成空字符串,或者空数组 否则会出现unknown
        // define options
        options: [ {
          id: 'a',
          label: 'a',
          children: [ {
            id: 'aa',
            label: 'aa',
          }, {
            id: 'ab',
            label: 'ab',
          } ],
        }, {
          id: 'b',
          label: 'b',
        }, {
          id: 'c',
          label: 'c',
        } ],
      }
    },
  }
</script>

详细的文档

注意绑定的数据结构是 id, label, children

{
  id: '<id>',
  label: '<label>',
  children: [
    {
      id: '<child id>',
      label: '<child label>',
    },
    ...
  ],
}

有时候后台传过来的数据结构的键不是 id, label, children,我们需要转换成符合要求的数据结构

    // 获取信息
    getAllDeps() {
      this.$axios.post("url").then(res => {
        if (res.data.responseCode === "200") {
         let tempArr=[]
          this.changeDepsDataName(res.data.data,tempArr)
          console.log(tempArr)
          this.options= tempArr
        }
      });
    },
    changeDepsDataName(dataArr, tepArr){
      for( let i=0;i<dataArr.length;i++){
        let obj={}
        obj.id = dataArr[i].id
        obj.label = dataArr[i].departmentName
        if(dataArr[i].childDepartment && dataArr[i].childDepartment.length){
          obj.children = this.changeDepsDataName(dataArr[i].childDepartment,[])
        }
        tepArr.push(obj)
      }
      return tepArr
    },

也可以设置 normalizer

<treeselect v-model="value" :multiple="true" :options="options" :normalizer="normalizer"/>
//后台返回的数据如果和VueTreeselect要求的数据结构不同,需要进行转换
normalizer(node){
    //去掉children=[]的children属性
    if(node.children && !node.children.length){
        delete node.children;
    }
    return {
        id: node.id,
        label:node.name,
        children:node.children
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!