树形组件
一、树形组件
简单来说就是一个简单地三级列表菜单。
解构和逻辑都非常简单,主要还是考验自己对所学知识的应用。这里的注释比较少,不懂可以多思考。
//
<template>
<div class="#app">
<base-tree :data="data"/>
</div>
</template>
<script>
import BaseTree from "./Tree";//导入组件
export default {
components: {
BaseTree //定义组件名
},
data(){
return {
data: [{
label: "一级 1",
children: [
{
label: "二级 1-1",
children: [
{
label: "三级 1-1-1"
}
]
}
]
},
{
label: "一级 2",
children: [
{
label: "二级 2-1",
children: [
{
label: "三级 2-1-1"
}
]
},
{
label: "二级 2-2",
children: [
{
label: "三级 2-2-1"
}
]
}
]
},
{
label: "一级 3",
children: [
{
label: "二级 3-1",
children: [
{
label: "三级 3-1-1"
}
]
},
{
label: "二级 3-2",
children: [
{
label: "三级 3-2-1"
}
]
}
]
}]
}
}
}
</script>
<template>
<ul class="tree">
<li class="tree-node" v-for="(node,index) in data" :key="node[defaultProps.label]">
<i class="iconfont" v-if="node[defaultProps.children]"
:class="{
'icon-down': !showChildren[index],//打开就更换图标
'icon-right': showChildren[index]
}"></i>
<span class="node-label" @click="handleClick(index)">
{
{ node[defaultProps.label] }}
</span>
<keep-alive>//缓存状态,上次怎么打开的闭合后再打开是一样的
<base-tree :data="node[defaultProps.children]"
v-if="showChildren[index] && node[defaultProps.children]"/>//如果子菜单不存在就不显示,否则最后一级菜单点击会报错
</keep-alive>
</li>
</ul>
</template>
<script>
export default {
name: 'base-tree',
props: {
data: {
type: Array,
required: true
},
defaultProps: {
type: Object,
default: ()=>({
label: 'label',
children: 'children'
})
}
},
data(){
return {
showChildren: []
}
},
methods: {
handleClick(index) {
const flag = !this.showChildren[index];//判断子菜单,不存在就显示
this.showChildren[index] = !this.showChildren[index];
this.$set(this.showChildren,index,flag);
},
},
mounted(){
// console.log(this.data);
}
}
</script>
<style scoped>
@import "./assets/font.css";//这里主要是引入一些图标,可以在阿里图标库自行下载
li{
list-style: none;
}
.tree-node{
font-size: 14px;
cursor: pointer;
}
.tree-node .iconfont{
color: #c0c4cc;
font-size: 12px;
margin-right: 5px;
vertical-align: middle;
}
.tree-node .node-label {
font-size: 14px;
color: #606266;
vertical-align: middle;
}
</style>