vue实现菜单切换
动态路由与组件切换
使用Vue Router实现菜单切换是最常见的方式。在路由配置中定义菜单对应的组件路径,通过<router-link>或编程式导航切换视图。路由配置示例:
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({ history: createWebHistory(), routes })
菜单模板中使用<router-link>:
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
条件渲染与状态管理
通过Vue的v-if或v-show结合状态管理(如Pinia/Vuex)控制菜单内容显示。定义状态管理中的当前菜单标识:
// Pinia示例
export const useMenuStore = defineStore('menu', {
state: () => ({ currentMenu: 'home' })
})
在组件中根据状态切换内容:
<div v-if="currentMenu === 'home'">首页内容</div>
<div v-else-if="currentMenu === 'about'">关于内容</div>
组件动态加载
结合<component :is>实现动态组件切换。定义组件映射对象并绑定is属性:
const components = {
home: defineAsyncComponent(() => import('./Home.vue')),
about: defineAsyncComponent(() => import('./About.vue'))
}
模板中动态渲染:
<component :is="components[currentMenu]" />
嵌套路由与命名视图
适用于复杂布局场景。配置嵌套路由时使用children和命名视图(name属性):
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'settings', components: { default: Settings, sidebar: SettingsMenu } }
]
}
父组件中使用<router-view name="sidebar">指定渲染位置。
菜单高亮与激活状态
为当前选中菜单添加样式。Vue Router自动为激活的<router-link>添加router-link-active类,可通过CSS定制:
.router-link-active {
color: #42b983;
font-weight: bold;
}
或使用active-class属性指定自定义类名:
<router-link to="/home" active-class="menu-active">首页</router-link>
响应式菜单设计
结合媒体查询和Vue的响应式数据实现移动端适配。使用window.innerWidth监听屏幕变化:
const isMobile = ref(window.innerWidth < 768)
window.addEventListener('resize', () => {
isMobile.value = window.innerWidth < 768
})
模板中根据isMobile切换菜单形态(如折叠菜单):
<button v-if="isMobile" @click="toggleMenu">☰</button>
<nav v-show="!isMobile || menuExpanded">
<!-- 菜单项 -->
</nav>






