vue实现 树形下拉菜单
时间: 2023-09-04 07:13:06 浏览: 116
vue实现下拉菜单树
Vue可以通过递归组件的方式实现树形下拉菜单。
首先,定义一个树形节点组件,包括节点名称和子节点列表:
```
<template>
<li>
<span @click="toggle">{{ node.name }}</span>
<ul v-show="expanded">
<tree-node v-for="child in node.children" :node="child" :key="child.id"></tree-node>
</ul>
</li>
</template>
<script>
export default {
name: 'TreeNode',
props: {
node: {
type: Object,
required: true
}
},
data() {
return {
expanded: false
}
},
methods: {
toggle() {
this.expanded = !this.expanded
}
}
}
</script>
```
然后,在父组件中引入树形节点组件,使用递归方式渲染树形菜单:
```
<template>
<div>
<ul>
<tree-node v-for="node in treeData" :node="node" :key="node.id"></tree-node>
</ul>
</div>
</template>
<script>
import TreeNode from './TreeNode.vue'
export default {
name: 'TreeMenu',
components: {
TreeNode
},
data() {
return {
treeData: [
{
id: 1,
name: 'Node 1',
children: [
{
id: 2,
name: 'Node 1.1',
children: []
},
{
id: 3,
name: 'Node 1.2',
children: [
{
id: 4,
name: 'Node 1.2.1',
children: []
},
{
id: 5,
name: 'Node 1.2.2',
children: []
}
]
}
]
},
{
id: 6,
name: 'Node 2',
children: []
}
]
}
}
}
</script>
```
这样就可以实现一个简单的树形下拉菜单了。
阅读全文