<div id="app">
<tree :datalist='treeData'></tree>
</div>
<script>
const treeData = [
{
name: '一级 1',
children: [
{
name: '二级 1-1',
children: [
{
name: '三级 1-1-1',
children: [
{
name: '四级 1-1-1-1'
}
]
}
]
}
]
},
{
name: '一级 2',
children: [
{
name: '二级 2-1',
children: [
{
name: '三级 2-1-1'
}
]
}, {
name: '二级 2-2',
children: [
{
name: '三级 2-2-1',
}
]
}
]
},
{
name: '一级 3',
children: [
{
name: '二级 3-1',
children: [
{
name: '三级 3-1-1'
}
]
},
{
name: '二级 3-2',
children: [
{
name: '三级 3-1-1'
}
]
}
]
}
]
Vue.component('tree', {
props: ['datalist'],
data() {
return {
showChildren: [],
nohiddenChildren: []
}
},
template: `<ul>
<li v-for='(data,index) in datalist' :key='data.name'>
<span @click='handleClick(index)'>{{data.name}}</span>
<tree :datalist="data.children"
v-show="showChildren[index]"
v-if='nohiddenChildren[index]'></tree>
</li>
</ul>`,
methods: {
handleClick(index) {
this.showChildren.splice(index, 1, !this.showChildren[index])
this.nohiddenChildren.splice(index, 1, true)
}
}
})
new Vue({
el: '#app',
data: {
treeData
}
})
</script>
To achieve the effect
I mainly explain here why v-show and v-if such use:
1. Click on the title to open its sub-elements:
If you use the v-if as a control, each click on the title, sub-assemblies will re-render a back, can not be saved before the inner sub-elements open state, while the use of such frequent switching is possible to save more v-show dom rendering, saving performance.
2. Use the v-show, why do they use the v-if
If you simply use the v-show, the page initialization time, and all of sub-elements will be rendered, just use display: none; as a control, and on this page performance not very good at this time need to use the v-if, then click on the label rendering dom label.