vue实现分级导航栏
实现分级导航栏的基本思路
在Vue中实现分级导航栏通常涉及嵌套路由、组件递归或动态渲染菜单结构。核心是通过数据驱动视图,利用Vue的响应式特性和组件化能力构建层级关系。
数据结构设计
采用树形结构存储导航信息,例如:
const menuItems = [
{
title: "一级菜单1",
children: [
{ title: "二级菜单1-1", path: "/sub1-1" },
{ title: "二级菜单1-2", path: "/sub1-2" }
]
},
{
title: "一级菜单2",
children: [
{
title: "二级菜单2-1",
children: [
{ title: "三级菜单2-1-1", path: "/deep" }
]
}
]
}
]
递归组件实现
创建可递归调用的导航组件:
<template>
<ul>
<li v-for="item in items" :key="item.title">
<router-link v-if="!item.children" :to="item.path">
{{ item.title }}
</router-link>
<template v-else>
<span @click="toggleExpand(item)">{{ item.title }}</span>
<nav-menu
v-show="item.expanded"
:items="item.children"
class="submenu"
/>
</template>
</li>
</ul>
</template>
<script>
export default {
name: 'NavMenu',
props: ['items'],
methods: {
toggleExpand(item) {
this.$set(item, 'expanded', !item.expanded)
}
}
}
</script>
样式与交互优化
添加CSS实现视觉层级:

.submenu {
margin-left: 20px;
transition: all 0.3s ease;
}
ul {
list-style: none;
padding-left: 0;
}
li {
cursor: pointer;
padding: 8px 12px;
}
与Vue Router集成
在路由配置中匹配嵌套结构:
const routes = [
{
path: '/menu1',
component: Layout,
children: [
{ path: 'sub1', component: Sub1 },
{ path: 'sub2', component: Sub2 }
]
}
]
动态高亮当前路由
通过计算属性实现激活状态:

computed: {
activeRoute() {
return this.$route.path
}
}
模板中绑定激活类:
<router-link
:class="{ 'active': item.path === activeRoute }"
>
可配置化扩展
通过props接受外部配置:
props: {
items: {
type: Array,
required: true
},
collapseTransition: {
type: Boolean,
default: true
}
}
移动端适配
添加响应式处理:
data() {
return {
isMobile: window.innerWidth < 768
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.isMobile = window.innerWidth < 768
}
}






