组件递归常用到的栗子就比如树形结构的创建,需要自调用进行递归渲染
下面是递归组件渲染tree的效果图:
完整的代码仓库地址:https://github.com/HuangPingP/vue-tree
1、创建一个treeMenu.vue的组件文件,组件内调用必须定义name 才能自调用
<ul class="item">
<li >
<div :class="{bold: isFolder,'item-info':true}" @click="toggle" >
<!-- 伸缩图标 -->
<span
v-if="isFolder"
:class="{'iconfont':true,'icon-right-allow':!open,'icon-down-allow':open}">
</span>
<span class="item-name ellipsis">{{ model.name }}</span>
<!-- 操作栏 -->
<p class="edit-box">
<i class="iconfont icon-add" @click="addChild"></i>
<i class="iconfont icon-edit"></i>
<i class="iconfont icon-dele"></i>
</p>
</div>
<!-- 组件递归调用 -->
<ul class="item-child" v-show="open" v-if="isFolder">
<item
v-for="(model, index) in model.children"
:key="index"
:model="model">
</item>
</ul>
</li>
</ul>
import Vue from 'vue'
export default {
props: ['model'],
name: 'item', // 必须给组件命名
data() {
return {
open: true
}
},
computed: {
isFolder() {
return this.model.children &&
this.model.children.length
}
},
methods: {
toggle() {
if (this.isFolder) {
this.open = !this.open
}
},
addChild() {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.open = true
}
this.model.children.push({
name: 'new stuff'
})
}
}
}
2.调用组件 在helloWord.vue中调用 treeMenu.vue组件
<tree-menu :model="treeData"></tree-menu>
//数据结构
treeData:{
name: 'My Tree',
children: [
{ name: 'hello' },
{ name: 'watdfs' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
},
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
}
]
}
]
}