实现vue Tree展示样式
1、 创建tree可循环的子组件(tree-child)
<template>
<li>
<span @click="toggle">
<i v-if="hasChild" class="icon">{
{open ? '-' : '+'}}</i>
{
{ data.name }}
</span>
<ul v-show="open" v-if="hasChild">
<tree-child v-for="(item, index) in data.children" :data="item" :key="index"></tree-child>
</ul>
</li>
</template>
<script>
export default {
name: 'TreeChild',
props: {
data: {
type: [Object, Array],
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>
2、赋值数据(tree)
<template>
<div class="tree-menu">
<ul v-for="item in data">
<tree-child :data="item"></tree-child>
</ul>
</div>
</template>
<script>
import TreeChild from './tree-child'
export default {
props: {
data: {
type: [Object, Array],
required: true
}
},
components: {
TreeChild
}
}
</script>
3、component引用
<template>
<tree :data="treeData"></tree>
</template>
<script>
import Tree from './tree'
export default {
components: {
Tree
},
data() {
return {
treeData: [{
'name': '人员管理',
'children': [{
'name': '分组1',
'children': [{
'name': '人员1'
}, {
'name': '人员2'
}, {
'name': '人员3'
}]
}, {
'name': '分组2'
}, {
'name': '分组3'
}]
}, {
'name': '基础档案',
}, {
'name': '送货管理'
}]
}
},
}
</script>
React实现Tree
1、创建Tree
import React, {Component} from 'react';
export default class Tree extends Component {
constructor(props) {
super(props)
this.state = {
data: this.props.data || []
}
}
markTreeChild(data) {
let tree;
if (Object.prototype.toString.call(data) == "[object Array]") {
tree = data.map((item) => {
let treeChild = (<li key={this.count++}>{item.text}</li>)
if (item.children && item.children.length) {
treeChild = (<li key={this.count++}>
<span>{item.text}</span>
{this.markTreeChild(item.children)}
</li>)
}
return treeChild
})
}
return (
<ul>{tree}</ul>
)
}
render() {
this.count = 0
return this.markNode(this.state.data)
}
}
2、component
<Tree data={[{
'name': '人员管理',
'children': [{
'name': '分组1',
'children': [{
'name': '人员1'
}, {
'name': '人员2'
}, {
'name': '人员3'
}]
}, {
'name': '分组2'
}, {
'name': '分组3'
}]
}, {
'name': '基础档案',
}, {
'name': '送货管理'
}]}/>