生活随笔
收集整理的這篇文章主要介紹了
vue中递归组件实现多级列表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、遞歸組件的概念
遞歸組件:
遞歸組件簡單來說在組件內使用組件本身。這個在vue的項目開發中也是比較常見的。對于一些多級的數據嵌套,如果對于每一層數據都進行for循環嵌套,那會非常繁瑣,也很不方便。而如果使用遞歸組件,就可以一次性解決,嵌套層級簡單,可以實現多級列表。
二、遞歸組件的實現
父組件的data數據
name
: 'Home'
data () {return {list
: [{title
: '用戶管理',children
: [{title
: '會員用戶',children
: [{title
: '鉆石用戶'},{title
: '白銀用戶'},{title
: '黃金用戶'}]},{title
: '普通用戶'},{title
: '超級用戶'}]},{title
: '訂單管理',children
: [{title
: '訂單列表'},{title
: '退貨列表'}]},{title
: '商家管理',children
: [{title
: '普通商家'},{title
: '會員商家'}]},{title
: '權限管理',children
: [{title
: '用戶權限'},{title
: '管理員權限'}]}]}},
我們可以先進行第一層數據的遍歷,對于父組件,先進行綁定data中的數據list,在父組件調用的時候使用:list="list",然后子組件通過props進行接收數據list,最后通過v-for進行遍歷數據,顯示第一個層級的數據。完整代碼如下:
<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中使用遞歸組件,就是在遍歷第一個層級數據的里面,再次使用組件。通過進行v-for遍歷數據,子組件再次綁定數據 :list="item.children",進行遍歷,這樣就實現了遞歸組件,可以實現層層遍歷,實現多級列表。完整代碼如下:
<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>
顯示效果如下圖所示
總結
以上是生活随笔為你收集整理的vue中递归组件实现多级列表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。