这是一个递归组件,首先组件是可以在模板里通过 export default 的 name 来调用本身
只是一个思路,写的比较简单,直接上代码
<template>
<ul>
<li v-for="(item,index) in list" :key="index">
<p :class="group_head[index]" @click="changeStatus(index)">{{item.name}}</p>
<!-- 通过name: "treeMenus"调用自身 进行递归-->
<tree-menus v-if="status[index]" :list="item.cList"></tree-menus>
</li>
</ul>
</template>
<script>
export default {
name: "treeMenus",
props: {
list: {//接收父组件船只,并设置默认值
type: Array,
default: ()=>[]
}
},
data() {
return {
status: [],
has_branch: [],
group_head: []
}
},
methods: {
changeStatus(index) {
console.log(index)
if (this.status[index] == true) {//如果展开就折叠起来
this.$set(this.status, index, false) //this.$set 触发视图更新
} else {//没展开,根据是否有 clist 来判断能不能 展开
this.$set(this.status, index, this.has_branch[index])
}
//切换样式
if(this.group_head[index] == 'group'){
this.$set(this.group_head, index, 'group_s')
} else if(this.group_head[index] == 'group_s'){
this.$set(this.group_head, index, 'group')
}
},
initTree() {
if (this.list && this.list.length > 0) {
this.list.forEach((item, index) => {
this.status[index] = false //默认不展开
if ("cList" in item) {//判断有没有 cList
this.has_branch[index] = true
this.group_head[index] = "group"
} else {
this.group_head[index] = "nullcList"
this.has_branch[index] = false
}
})
}
}
},
created() {
console.log(this.list)
this.initTree()
}
}
</script>
<style>
ul{
list-style-type: none;
padding-left: 20px;
margin: 0;
}
p{
margin: 5px 0;
cursor: pointer;
background-color: bisque;
}
.group{
position: relative;
}
.group::after{
display: block;
position: absolute;
content: "";
width: 0px;
height: 0px;
transform: translate(0,-50%);
top: 50%;
left: -12px;
border-width:8px 0 8px 8px;
border-style:solid;
border-color:transparent transparent transparent #333;/*透明 透明 透明 灰*/
}
.group_s{
position: relative;
}
.group_s::after{
display: block;
position: absolute;
content: "";
width: 0px;
height: 0px;
transform: translate(0,-50%);
top: 50%;
left: -15px;
border-width:8px 8px 0 8px;;
border-style:solid;
border-color:#333 transparent transparent transparent;
}
</style>
在父组件中调用
<template>
<div>
<!-- 将list传递到子组件中 -->
<my-trees :list="list"></my-trees>
</div>
</template>
<script>
//引入tree组件
import myTrees from "./mytree";
export default {
//注册组件
components: {
myTrees
},
data() {
return {
list: [
{
name: "中国",
cList: [
{ name: "上海" },
{
name: "江西",
cList: [
{ name: "南昌市", cList: [{ name: "南昌县" }] }
]
}
]
},
{
name: "美国",
cList: [{ name: "纽约" }, { name: "落砂机" }]
},
{ name: "澳大利亚" }
]
}
}
}
</script>
<style>
</style>
最终效果: