vue实现树形tree展示组件封装

Posted chi1130

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue实现树形tree展示组件封装相关的知识,希望对你有一定的参考价值。

效果

在线demo🚀🐠

代码

TreeItem.vue


<template>
  <div class="tree-item">
    <div @click="handleToggle" class="tree-title">
      <i v-if="hasChild" :class="open?'el-icon-remove-outline':'el-icon-circle-plus-outline'"></i>
      <h4> list.label </h4>
    </div>
    <div v-show='open'  class="child-content">
      <tree-item
        v-for="(item, index) in list.children"
        :list="item"
        :key="index"
      ></tree-item>
    </div>
  </div>
</template>

<script>
export default 
  name: "TreeItem",
  props: 
    list: 
      type: [Object, Array],
      required: true
    
  ,
  data() 
    return 
      open: false
    ;
  ,
  computed: 
    hasChild() 
      return this.list.children && this.list.children.length;
    
  ,
  methods: 
    handleToggle() 
      if (this.hasChild) 
        this.open = !this.open;
      
    
  
;
</script>

<style lang='less' scoped>
.tree-item
  font-size: 20px;
  cursor: pointer;
  .tree-title
    display: flex;
    justify-content: flex-start;
    align-items: center;
  

.child-content
  margin-left: 50px;

</style>

Tree.vue



<template>
  <div class="tree-wrap">
    <div v-for="(item, index) in dataSource" :key="index">
      <tree-item :list="item"></tree-item>
    </div>
  </div>
</template>

<script>
import TreeItem from "./TreeItem";
export default 
  name: 'tree',
  props: 
    dataSource: 
      type: [Object, Array],
      required: true
    
  ,
  components: 
    TreeItem
  
;
</script>
<style scoped>
.tree-wrap
  width: 100%;
  /* padding: 0 50px; */

</style>


your component.vue


<template>
   <div class="tree-w">
     <x-tree :data-source="myData"></x-tree>
   </div>
</template>
<script>
import xTree from './Tree.vue'
export default 
  name: 'trees',
  components: 
    xTree
  ,
  data() 
    return 
      myData: [
        label: '一级 1',
        children: [
          label: '二级 1-1',
          children: [
            label: '三级 1-1-1'
          ]
        ]
      , 
        label: '一级 2',
        children: [
          label: '二级 2-1',
          children: [
            label: '三级 2-1-1'
          ]
        , 
          label: '二级 2-2',
          children: [
            label: '三级 2-2-1'
          ]
        ]
      , 
        label: '一级 3',
        children: [
          label: '二级 3-1',
          children: [
            label: '三级 3-1-1'
          ]
        , 
          label: '二级 3-2',
          children: [
            label: '三级 3-2-1'
          ]
        ]
      ],
    
  

</script>
<style>
.tree-w
  padding: 50px;
  padding-left: 200px;

</style>

以上是关于vue实现树形tree展示组件封装的主要内容,如果未能解决你的问题,请参考以下文章

vue实现树形tree展示组件封装

vue实现树形tree展示组件封装

封装树形组件 只有一个跟节点

vue 树形结构展示

vue-table-with-tree-grid的树形表格组件如何使用

iview组件库:自定义方法去控制Tree树形数据的根节点与叶节点的关联性