vue动态菜单动态路由
时间: 2023-09-20 14:09:23 浏览: 97
实现动态菜单和动态路由的方法如下:
1. 在后端定义菜单和路由的数据结构,例如:
```
{
"menus": [
{
"name": "首页",
"icon": "el-icon-s-home",
"path": "/dashboard",
"children": []
},
{
"name": "用户管理",
"icon": "el-icon-user",
"path": "/user",
"children": [
{
"name": "用户列表",
"path": "/user/list"
},
{
"name": "新增用户",
"path": "/user/add"
}
]
}
],
"routes": [
{
"name": "Dashboard",
"path": "/dashboard",
"component": "Dashboard"
},
{
"name": "用户列表",
"path": "/user/list",
"component": "UserList"
},
{
"name": "新增用户",
"path": "/user/add",
"component": "UserAdd"
}
]
}
```
2. 在前端根据后端返回的数据生成菜单和路由,例如:
```
// 生成路由
function generateRoutesFromMenu(routes, menus) {
menus.forEach(menu => {
if (menu.path) {
const route = {
path: menu.path,
name: menu.name,
component: () => import(`@/views/${menu.path}.vue`)
};
routes.push(route);
}
if (menu.children) {
generateRoutesFromMenu(routes, menu.children);
}
});
}
// 生成菜单
function generateMenusFromRoutes(routes) {
const menus = [];
routes.forEach(route => {
if (route.path !== '/') {
const menu = {
name: route.name,
path: route.path
};
menus.push(menu);
}
});
return menus;
}
// 定义路由
const router = new VueRouter({
mode: 'history',
routes: []
});
// 获取后端返回的菜单和路由数据
axios.get('/api/menus').then(response => {
const menus = response.data.menus;
const routes = response.data.routes;
generateRoutesFromMenu(routes, menus);
router.addRoutes(routes);
const dynamicMenus = generateMenusFromRoutes(routes);
// 将菜单存入 Vuex 中
store.commit('setMenus', dynamicMenus);
});
```
3. 在前端页面中根据菜单和路由展示页面和菜单,例如:
```
// 显示菜单
<el-menu :default-active="$route.path" class="el-menu-vertical-demo" :router="true" :collapse="collapse">
<div class="logo">
<img src="@/assets/logo.png" alt="logo"/>
<span v-show="!collapse">Vue Admin</span>
</div>
<el-submenu v-for="menu in menus" :key="menu.path" :index="menu.path">
<template slot="title">
<i :class="menu.icon"></i>
<span>{{ menu.name }}</span>
</template>
<el-menu-item v-for="child in menu.children" :key="child.path" :index="child.path">{{ child.name }}</el-menu-item>
</el-submenu>
</el-menu>
// 显示页面
<template>
<div class="dashboard">
<h1>{{title}}</h1>
<p>{{content}}</p>
</div>
</template>
<script>
export default {
name: 'Dashboard',
data() {
return {
title: 'Dashboard',
content: 'Welcome to Vue Admin!'
}
}
}
</script>
<style scoped>
.dashboard {
text-align: center;
}
</style>
```
这样就可以实现动态菜单和动态路由了。
阅读全文