Vue-component | 極其簡易Tree列表

日常開發中積累了不少可能對一些開發有幫助的簡單易用的組件,好記性不如爛筆頭,想對過去的一些零零亂亂的東西做一些總結,反省自己的同時也便於思考一些更優的方法,提升下開發思維😉😉😉。
代碼傳送門(😃感覺有作用的的同學幫忙點下❤️️)

效果截圖

這是一個簡單的樹形列表,可展開收起。


組件結構

由多層列表嵌套組成。

<ul>
    <li>
        <ul>
            <li>...</li>
         </ul>
    </li>
</ul>

核心代碼

Tree
最頂層結構

<template>
  <ul>
    <item :model="model" />
  </ul>
</template>
<script>
import Item from './Item'
export default {
  name: 'j-tree',
  components: { Item },
  props: {
    model: Object
  }
}
</script>

Item
遞歸調用自己的核心

<template>
  <li>
    <div @click="toggle">
      {{model.title}}
      <span>[{{isOpen?"-":"+"}}]</span>
    </div>
    <ul v-show="isOpen" class="item">
      //    遞歸組件自己本身,要記得加上name,不然找不到自己。
      <item v-for="(item, index) in model.children" :key="index" :model="item" />
    </ul>
  </li>
</template>
<script>
export default {
  name: 'item',
  components: {},
  props: {
    model: Object
  },
  data () {
    return {
      isOpen: false
    }
  },
  methods: {
    toggle () {
      this.isOpen = !this.isOpen
    }
  }
}
</script>

傳入的數據格式

treeData: {
        title: '地球',
        children: [
          {
            title: '人'
          },
          {
            title: '水果',
            children: [
              {
                title: '橘子'
              },
              {
                title: '蘋果'
              }
            ]
          },
          {
            title: '植物',
            children: [
              {
                title: '四君子',
                expand: true,
                children: [
                  {
                    title: '梅'
                  },
                  {
                    title: '蘭'
                  },
                  {
                    title: '竹'
                  }
                ]
              },
              {
                title: '動物',
                children: [
                  {
                    title: '豬🐷'
                  },
                  {
                    title: '狗'
                  }
                ]
              },
              {
                title: '氣體',
                children: [
                  {
                    title: '空氣',
                    children: [
                      {
                        title: '氧氣'
                      }]
                  }]
              }
            ]
          }
        ]
      }

關鍵點


在這裏主要使用的一些技術包括:

技術 概述 備註
遞歸組件 自己調用自己,要記得註明name /
v-for 在這裏搭配遞歸,將數據一層一層遍歷展示 /

後續會持續更新其他一些有用的組件提供參考...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章