基于Vue技術(shù)實(shí)現(xiàn)遞歸組件的方法
描述
本文介紹的是基于Vue技術(shù)實(shí)現(xiàn)遞歸組件的方法。用Vue實(shí)現(xiàn)一級(jí)列表、二級(jí)列表的展示很簡單,但是想要實(shí)現(xiàn)無限級(jí),光是套上一個(gè)又一個(gè)的v-for是行不通的,這個(gè)時(shí)候就需要用到遞歸的方法,所謂遞歸,就是不斷調(diào)用自身,遞歸組件就是不斷調(diào)用自身組件來實(shí)現(xiàn)無限級(jí)列表展示。如下圖:

代碼實(shí)現(xiàn)
1、tree組件
在目錄下創(chuàng)建一個(gè) 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: [],
},
// 是否默認(rèn)展開全部
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;
}
/* ----------- 圖標(biāo)樣式 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);
}
/* ----------- 圖標(biāo)樣式 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: '一級(jí)列表1',
children: [
{
title: '二級(jí)列表1',
children: [
{
title: '三級(jí)列表1',
}
]
},
{
title: '二級(jí)列表2',
}
]
},
{
title: '一級(jí)列表2',
children: [
{
title: '二級(jí)列表1',
},
{
title: '二級(jí)列表2',
}
]
},
{
title: '一級(jí)列表3',
children: [
{
title: '三級(jí)列表1',
},
{
title: '三級(jí)列表2',
},
{
title: '三級(jí)列表3',
}
]
}
]
}
}
}
</script>
效果圖

總結(jié)
該組件只實(shí)現(xiàn)了數(shù)據(jù)展示以及一些基本功能,肯定是不滿足一些項(xiàng)目上的實(shí)際需求,若要使用,還需自己在此基礎(chǔ)上去拓展完善。(例如使用該組件實(shí)現(xiàn)左側(cè)菜單,可以自己配置數(shù)據(jù),稍微修改下組件模板,實(shí)現(xiàn)點(diǎn)擊跳轉(zhuǎn))。
組件功能
- 點(diǎn)擊展開和收起
- 是否展開全部
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue動(dòng)態(tài)添加表單validateField驗(yàn)證功能實(shí)現(xiàn)
這篇文章主要介紹了vue動(dòng)態(tài)添加表單validateField驗(yàn)證功能實(shí)現(xiàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

