vue实现菜单
Vue 实现菜单的方法
使用 Vue Router 实现动态菜单
通过 Vue Router 可以轻松实现动态菜单,结合路由配置生成菜单项。以下是一个基本示例:
// router/index.js
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
meta: { title: '首页', icon: 'home' }
},
{
path: '/about',
name: 'About',
component: About,
meta: { title: '关于', icon: 'info' }
}
]
<!-- Menu.vue -->
<template>
<div class="menu">
<router-link
v-for="route in menuRoutes"
:key="route.path"
:to="route.path"
>
<i :class="route.meta.icon"></i>
{{ route.meta.title }}
</router-link>
</div>
</template>
<script>
export default {
computed: {
menuRoutes() {
return this.$router.options.routes.filter(route => route.meta)
}
}
}
</script>
使用递归组件实现多级菜单
对于多级菜单,可以使用递归组件实现:
<!-- MenuItem.vue -->
<template>
<li>
<div @click="toggle">
{{ item.name }}
<span v-if="hasChildren">{{ isOpen ? '-' : '+' }}</span>
</div>
<ul v-show="isOpen && hasChildren">
<MenuItem
v-for="child in item.children"
:key="child.id"
:item="child"
/>
</ul>
</li>
</template>
<script>
export default {
name: 'MenuItem',
props: {
item: Object
},
data() {
return {
isOpen: false
}
},
computed: {
hasChildren() {
return this.item.children && this.item.children.length
}
},
methods: {
toggle() {
if (this.hasChildren) {
this.isOpen = !this.isOpen
}
}
}
}
</script>
使用 UI 框架实现菜单
主流 UI 框架如 Element UI、Ant Design Vue 都提供了现成的菜单组件:
<template>
<el-menu
:default-active="activeIndex"
mode="horizontal"
@select="handleSelect"
>
<el-menu-item index="1">首页</el-menu-item>
<el-submenu index="2">
<template #title>产品</template>
<el-menu-item index="2-1">产品1</el-menu-item>
<el-menu-item index="2-2">产品2</el-menu-item>
</el-submenu>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: '1'
}
},
methods: {
handleSelect(key, keyPath) {
console.log(key, keyPath)
}
}
}
</script>
实现权限控制菜单
结合权限系统可以实现动态菜单渲染:
// 过滤有权限的菜单
function filterAsyncRoutes(routes, roles) {
return routes.filter(route => {
if (hasPermission(roles, route.meta?.roles)) {
if (route.children) {
route.children = filterAsyncRoutes(route.children, roles)
}
return true
}
return false
})
}
响应式菜单实现
通过 CSS 媒体查询和 Vue 数据绑定可以实现响应式菜单:

<template>
<div class="menu-container">
<button @click="toggleMobileMenu">菜单</button>
<nav :class="{ 'mobile-menu': isMobile, 'show': showMobileMenu }">
<!-- 菜单内容 -->
</nav>
</div>
</template>
<script>
export default {
data() {
return {
isMobile: false,
showMobileMenu: false
}
},
mounted() {
this.checkScreenWidth()
window.addEventListener('resize', this.checkScreenWidth)
},
methods: {
checkScreenWidth() {
this.isMobile = window.innerWidth < 768
},
toggleMobileMenu() {
this.showMobileMenu = !this.showMobileMenu
}
}
}
</script>






