Vue递归组件
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
開始
在js/jsx中,我們可以通過遞歸的方式來生成一些有規(guī)律的dom結(jié)構,那么,在Vue模板中,我們能不能遞歸生成dom呢?答案是肯定的。在Vue中,組件可以遞歸的調(diào)用自己本身,但是有一些條件:
Demo
下面為了方便理解遞歸組件,我寫了一個小的demo:
有這么一份數(shù)據(jù),我們希望能把它做成像文件樹一樣的結(jié)果
[{'name': 'Vue','children': [{'name': '模板語法'},{'name': '計算屬性'},{'name': '生命周期','children': [{'name': 'beforeCreate'},{'name': 'created'},{'name': 'beforeMount'},{'name': 'mounted'},{'name': 'beforeUpdate'},{'name': 'updated'},{'name': 'beforeDestroy'},{'name': 'destroyed'}]}]},{'name': 'React','children': [{'name': 'jsx'},{'name': '生命周期'}]},{'name': 'Angular'} ]先寫我們的樹組件Tree.vue
<template><li><span @click="toggle"><i v-if="hasChild" class="icon" :class="[open ? 'folder-open': 'folder']"></i><i v-if="!hasChild" class="icon file-text"></i>{{ data.name }}</span><ul v-show="open" v-if="hasChild"><tree-menu v-for="(item, index) in data.children" :data="item" :key="index"></tree-menu></ul></li> </template><script> export default {name: 'TreeMenu',props: {data: {type: Object,required: true}},data() {return {open: false}},computed: {hasChild() {return this.data.children && this.data.children.length}},methods: {toggle() {if(this.hasChild) {this.open = !this.open}}} } </script><style> ul {list-style: none;margin: 10px 0; } li {padding: 3px 0; } li > span {cursor: pointer;font-size: 14px;line-height: 20px; } i.icon {display: inline-block;width: 20px;height: 20px;margin-right: 5px;background-repeat: no-repeat;vertical-align: middle; } .icon.folder {background-image: url("../assets/images/folder.svg"); } .icon.folder-open {background-image: url("../assets/images/folder-open.svg"); } .icon.file-text {background-image: url("../assets/images/file.svg"); } .tree-menu li {line-height: 1.5; } </style>可以看到,我們在Tree組件中有個name選項,值為TreeMenu,然后組件內(nèi)部調(diào)用TreeMenu本身,通過v-for來進行遞歸條件的判斷,這就形成了一個遞歸組件
然后我們在外部App.vue調(diào)用Tree組件
<template><div class="tree-menu"><ul v-for="item in data"><my-tree :data="item"></my-tree></ul></div> </template><script> var myData = [{'name': 'Vue','children': [{'name': '模板語法'},{'name': '計算屬性'},{'name': '生命周期','children': [{'name': 'beforeCreate'},{'name': 'created'},{'name': 'beforeMount'},{'name': 'mounted'},{'name': 'beforeUpdate'},{'name': 'updated'},{'name': 'beforeDestroy'},{'name': 'destroyed'}]}]},{'name': 'React','children': [{'name': 'jsx'},{'name': '生命周期','children': []}]},{'name': 'Angular'} ];import MyTree from './components/Tree' export default {components: {MyTree},data() {return {data: myData}} } </script>最終效果如圖:
結(jié)束
雖然這篇博客看起來很簡單,只是一個小的知識點,但是Vue的遞歸組件確實是一個非常強大的功能。可以用來實現(xiàn)一些類似文件樹、部門樹、級聯(lián)選擇這樣的組件,在實際業(yè)務開發(fā)中這些組件也經(jīng)常用到,還是非常重要的~
原文地址:http://blog.yuantang.site/2017/08/17/Vue遞歸組件
轉(zhuǎn)載于:https://my.oschina.net/prettypice/blog/1512498
總結(jié)
- 上一篇: 单链表Java实现
- 下一篇: 10分钟学会vue滚动行为