生活随笔
收集整理的這篇文章主要介紹了
vue中递归组件实现多级列表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、遞歸組件的概念
遞歸組件:
遞歸組件簡單來說在組件內(nèi)使用組件本身。這個(gè)在vue的項(xiàng)目開發(fā)中也是比較常見的。對于一些多級(jí)的數(shù)據(jù)嵌套,如果對于每一層數(shù)據(jù)都進(jìn)行for循環(huán)嵌套,那會(huì)非常繁瑣,也很不方便。而如果使用遞歸組件,就可以一次性解決,嵌套層級(jí)簡單,可以實(shí)現(xiàn)多級(jí)列表。
二、遞歸組件的實(shí)現(xiàn)
父組件的data數(shù)據(jù)
name
: 'Home'
data () {return {list
: [{title
: '用戶管理',children
: [{title
: '會(huì)員用戶',children
: [{title
: '鉆石用戶'},{title
: '白銀用戶'},{title
: '黃金用戶'}]},{title
: '普通用戶'},{title
: '超級(jí)用戶'}]},{title
: '訂單管理',children
: [{title
: '訂單列表'},{title
: '退貨列表'}]},{title
: '商家管理',children
: [{title
: '普通商家'},{title
: '會(huì)員商家'}]},{title
: '權(quán)限管理',children
: [{title
: '用戶權(quán)限'},{title
: '管理員權(quán)限'}]}]}},
我們可以先進(jìn)行第一層數(shù)據(jù)的遍歷,對于父組件,先進(jìn)行綁定data中的數(shù)據(jù)list,在父組件調(diào)用的時(shí)候使用:list="list",然后子組件通過props進(jìn)行接收數(shù)據(jù)list,最后通過v-for進(jìn)行遍歷數(shù)據(jù),顯示第一個(gè)層級(jí)的數(shù)據(jù)。完整代碼如下:
<template><div><div class="item" v-for="(item, index) of list" :key="index"><div class="item-title border-bottom">{{ item.title }}
</div></div></div>
</template><script>
export default {name: 'Detail',props: {list: Array}
}
</script><style lang="stylus" scoped>.item-titleline-height: .8remfont-size: .32rempadding: 0 .2rem.item-childrenpadding: 0 .2rem
</style
顯示效果如下圖所示
在vue中使用遞歸組件,就是在遍歷第一個(gè)層級(jí)數(shù)據(jù)的里面,再次使用組件。通過進(jìn)行v-for遍歷數(shù)據(jù),子組件再次綁定數(shù)據(jù) :list="item.children",進(jìn)行遍歷,這樣就實(shí)現(xiàn)了遞歸組件,可以實(shí)現(xiàn)層層遍歷,實(shí)現(xiàn)多級(jí)列表。完整代碼如下:
<template><div><div class="item" v-for="(item, index) of list" :key="index"><div class="item-title border-bottom">{{ item.title }}
</div><div v-if="item.children" class="item-children"><detail :list="item.children"></detail></div></div></div>
</template><script>
export default {name: 'Detail',props: {list: Array}
}
</script><style lang="stylus" scoped>.item-titleline-height: .8remfont-size: .32rempadding: 0 .2rem.item-childrenpadding: 0 .2rem
</style>
顯示效果如下圖所示
總結(jié)
以上是生活随笔為你收集整理的vue中递归组件实现多级列表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。