写一个tree组件的 vue3.0的代码
时间: 2023-04-04 07:01:33 浏览: 76
以下是一个简单的 Vue 3. Tree 组件的代码:
<template>
<div class="tree">
<ul>
<li v-for="node in nodes" :key="node.id">
<span @click="toggleNode(node)">
{{ node.name }}
</span>
<tree v-if="node.children && node.expanded" :nodes="node.children"></tree>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Tree',
props: {
nodes: {
type: Array,
required: true
}
},
data() {
return {
expandedNodes: []
}
},
methods: {
toggleNode(node) {
if (node.children) {
node.expanded = !node.expanded;
if (node.expanded) {
this.expandedNodes.push(node.id);
} else {
const index = this.expandedNodes.indexOf(node.id);
if (index !== -1) {
this.expandedNodes.splice(index, 1);
}
}
}
}
},
created() {
this.nodes.forEach(node => {
if (this.expandedNodes.includes(node.id)) {
node.expanded = true;
}
});
}
}
</script>
<style>
.tree {
margin-left: 20px;
}
.tree ul {
list-style-type: none;
margin: ;
padding: ;
}
.tree li {
margin: ;
padding: 1em;
position: relative;
}
.tree li::before {
content: '';
position: absolute;
top: ;
bottom: ;
left: -.5em;
border-left: 1px solid #ccc;
}
.tree li::after {
content: '';
position: absolute;
top: .5em;
left: -.5em;
width: 1em;
height: .5em;
border-bottom: 1px solid #ccc;
border-left: 1px solid #ccc;
transform: rotate(-45deg);
}
.tree li:last-child::before {
height: 50%;
}
.tree li:last-child::after {
display: none;
}
.tree li > ul {
margin-top: .5em;
margin-bottom: .5em;
margin-left: 1em;
padding-left: 1em;
border-left: 1px solid #ccc;
display: none;
}
.tree li.expanded > ul {
display: block;
}
.tree li > span {
cursor: pointer;
}
</style>
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)