前端把页面的路由路径给后台,路径前面尽量带 "@/"比较好,让后台根据不同的角色权限,返回给前端指定的动态路由列表,请求到路由列表后,使用 “addRoutes” 添加到路由里去(官网给的方法)。title表示中文,path表示跳转的路由,这样路由菜单就有了
案例:
home.vue
<template>
<div>
<button @click="onlogin">登录按钮</button>
</div>
</template>
<script>
export default {
methods: {
onlogin() {
// 动态路由:asyncRoutes 模拟从后台请求到的动态数据路由列表
let asyncRoutes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue'),
meta: {
title: "首页"
},
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('@/views/Dashboard.vue')
meta: {
title: "仪表盘页"
},
}
]
var timer = setTimeout(() => {
this.$router.addRoutes(asyncRoutes);// 把动态路由列表使用 “addRoutes” 添加进去
clearTimeout(timer);
timer = null;
}, 1000);
},
},
};
</script>
本地的router: router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 普通路由
export const constantRouts = [
{
path: '/login',
name: 'login',
component: () => import('@/views/Login.vue'),
meta: {
title: "登录页"
},
},
{
path: '/register',
name: 'register',
component: () => import('@/views/Register.vue'),
meta: {
title: "注册页"
},
},
]
const router = new VueRouter({
routes: constantRouts
})
export default router