使用vue做一个树状目录
时间: 2024-03-04 14:49:13 浏览: 21
好的,下面是一个简单的vue树状目录代码实现:
首先,你需要一个数据源来表示树状目录的结构,比如:
```javascript
data: {
treeData: [
{
id: 1,
label: '一级目录1',
children: [
{
id: 2,
label: '二级目录1',
children: [
{
id: 3,
label: '三级目录1'
},
{
id: 4,
label: '三级目录2'
}
]
},
{
id: 5,
label: '二级目录2'
}
]
},
{
id: 6,
label: '一级目录2',
children: [
{
id: 7,
label: '二级目录3'
}
]
}
]
}
```
接下来,在模板中使用递归的方式来渲染树状目录:
```html
<template>
<div>
<ul>
<li v-for="item in treeData" :key="item.id">
{{ item.label }}
<tree-item :children="item.children" />
</li>
</ul>
</div>
</template>
<script>
export default {
components: {
TreeItem: {
props: ['children'],
template: `
<ul v-if="children">
<li v-for="child in children" :key="child.id">
{{ child.label }}
<tree-item :children="child.children" />
</li>
</ul>
`
}
},
data() {
return {
treeData: [/*...*/]
}
}
}
</script>
```
这个例子中,我们定义了一个 `TreeItem` 组件,它接收一个 `children` 属性来表示它的子节点。在模板中,我们使用 `v-for` 来遍历当前节点的子节点,并递归地使用 `TreeItem` 组件来渲染子节点。
最后,你可以自定义组件样式来美化树状目录的外观。
相关推荐
![](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)