Tree组件是典型的递归组件,其他的诸如菜单组件都属于这⼀一类,也是相当常见的。
组件设计
Tree组件最适合的结构是无序列列表ul,创建一个递归组件Item表示Tree选项,如果当前Item存在 children,则递归渲染子树,以此类推;同时添加一个标识管理理当前层级item的展开状态。
实现Item组件
{ {model.title}}
[{ {open ? '-' : '+'}}]
export default {
name: "Item",
props: {
model: Object
},
data: function() {
return {
open: false // 打开状态
};
},
computed: {
isFolder: function() { // 是否有子树
return this.model.children && this.model.children.length;
}
},
methods: {
toggle: function() {
if (this.isFolder) {
this.open = !this.open;
}
},
}
};
使⽤
import Item