js实现四层树形菜单
实现四层树形菜单的方法
数据结构设计
使用嵌套对象或数组表示树形结构,每个节点包含id、label、children等属性。例如:
const treeData = [
{
id: 1,
label: '一级菜单',
children: [
{
id: 11,
label: '二级菜单',
children: [
{
id: 111,
label: '三级菜单',
children: [
{ id: 1111, label: '四级菜单' }
]
}
]
}
]
}
];
递归渲染组件
通过递归组件渲染每一层菜单,Vue/React示例:
// React组件示例
function TreeNode({ node }) {
return (
<li>
{node.label}
{node.children && (
<ul>{node.children.map(child => <TreeNode node={child} />)}</ul>
)}
</li>
);
}
样式控制
使用CSS控制缩进和展开状态:
.tree ul {
padding-left: 20px;
}
.tree li {
list-style-type: none;
cursor: pointer;
}
交互功能实现
添加展开/折叠功能:
function toggleExpand(node) {
node.isExpanded = !node.isExpanded;
// 触发视图更新
}
动态加载优化
对于大数据量可采用懒加载:

async function loadChildren(parentId) {
const res = await fetch(`/api/menu?parent=${parentId}`);
return res.json();
}
完整示例代码
// Vue组件示例
Vue.component('tree-menu', {
props: ['node'],
template: `
<li>
<span @click="toggle">{{node.label}}</span>
<ul v-if="showChildren">
<tree-menu v-for="child in node.children" :node="child"/>
</ul>
</li>
`,
data() {
return { isExpanded: false }
},
computed: {
showChildren() {
return this.node.children && this.isExpanded
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
})






