基于Vue技術(shù)實現(xiàn)遞歸組件的方法
描述
本文介紹的是基于Vue技術(shù)實現(xiàn)遞歸組件的方法。用Vue實現(xiàn)一級列表、二級列表的展示很簡單,但是想要實現(xiàn)無限級,光是套上一個又一個的v-for是行不通的,這個時候就需要用到遞歸的方法,所謂遞歸,就是不斷調(diào)用自身,遞歸組件就是不斷調(diào)用自身組件來實現(xiàn)無限級列表展示。如下圖:
代碼實現(xiàn)
1、tree組件
在目錄下創(chuàng)建一個 tree.vue 的組件。
<!-- tree 樹形組件 --> <template> <div class="container"> <div v-for="item in treeData" :key="item"> <div class="row" @click="extend(item)"> <span ref="icon" class="icon-common" :class="{ 'icon-down': item.children, 'icon-radio': !item.children, 'icon-rotate': item.isExtend }" ></span> <span class="title">{{ item.title }}</span> </div> <div v-if="isExtend(item)" class="children"> <tree :tree-data="item.children" :is-extend-all="isExtendAll" /> </div> </div> </div> </template> <script> export default { props: { // 組件數(shù)據(jù) treeData: { type: Array, default: [], }, // 是否默認展開全部 isExtendAll: { type: Boolean, default: true, } }, methods: { // 展開列表 extend(item) { if (item.children) { item.isExtend = !item.isExtend; } }, isExtend(item) { const isExtend = !item.isExtend && true; return this.isExtendAll ? isExtend : !isExtend; } } } </script> <style scoped> .container { font-size: 14px; } .row { display: flex; align-items: center; cursor: pointer; margin-bottom: 10px; } /* ----------- 圖標樣式 START ------------- */ .icon-common { display: inline-block; transition: all .3s; } .icon-down { width: 0; height: 0; border: 4px solid transparent; border-top: 6px solid #000; border-bottom: none; } .icon-radio { width: 6px; height: 6px; background: #000; border-radius: 50%; } .icon-rotate { transform: rotate(-90deg); } /* ----------- 圖標樣式 END ------------- */ .title { margin-left: 10px; } .children { padding-left: 20px; } </style>
2、引用
在需要用到 tree 組件的地方引入該組件。
<template> <tree :tree-data="treeData" /> </template> <script> import Tree from './components/tree.vue'; export default { components: { Tree, }, data() { return { treeData: [ { title: '一級列表1', children: [ { title: '二級列表1', children: [ { title: '三級列表1', } ] }, { title: '二級列表2', } ] }, { title: '一級列表2', children: [ { title: '二級列表1', }, { title: '二級列表2', } ] }, { title: '一級列表3', children: [ { title: '三級列表1', }, { title: '三級列表2', }, { title: '三級列表3', } ] } ] } } } </script>
效果圖
總結(jié)
該組件只實現(xiàn)了數(shù)據(jù)展示以及一些基本功能,肯定是不滿足一些項目上的實際需求,若要使用,還需自己在此基礎上去拓展完善。(例如使用該組件實現(xiàn)左側(cè)菜單,可以自己配置數(shù)據(jù),稍微修改下組件模板,實現(xiàn)點擊跳轉(zhuǎn))。
組件功能
- 點擊展開和收起
- 是否展開全部
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決echarts圖表使用v-show控制圖表顯示不全的問題
這篇文章主要介紹了解決echarts圖表使用v-show控制圖表顯示不全的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07vuecli3打包后出現(xiàn)跨域問題,前端配置攔截器無效的解決
這篇文章主要介紹了vuecli3打包后出現(xiàn)跨域問題,前端配置攔截器無效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06ant-design-vue table分頁onShowSizeChange后的pageNo解決
這篇文章主要介紹了ant-design-vue table分頁onShowSizeChange后的pageNo的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04