Vue实现动态路由

通常我们在vue项目中都是前端配置好路由的,但在一些项目中我们可能会遇到权限控制,这样我们就涉及到动态路由的设置了。

动态路由设置一般有两种:

(1)、简单的角色路由设置: 比如只涉及到管理员和普通用户的权限。通常直接在前端进行简单的角色权限设置

(2)、复杂的路由权限设置: 比如OA系统、多种角色的权限配置。通常需要后端返回路由列表,前端渲染使用

1、简单的角色路由设置

(1)配置项目路由权限

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
Vue.use(Router)
let asyncRoutes = [
    {
        path: '/permission',
        component: Layout,
        redirect: '/permission/page',
        alwaysShow: true, 
        name: 'Permission',
        meta: {
            title: 'Permission',
            roles: ['admin', 'editor'] // 普通的用户角色
        },
        children: [
            {
                path: 'page',
                component: () => import('@/views/permission/page'),
                name: 'PagePermission',
                meta: {
                    title: 'Page',
                    roles: ['editor']  //  editor角色的用户才能访问该页面
                }
            },
            {
                path: 'role',
                component: () => import('@/views/permission/role'),
                name: 'RolePermission',
                meta: {
                    title: 'Role',
                    roles: ['admin']    //  admin角色的用户才能访问该页面
                }
            }
        ]
    },
 
]
let router = new Router({
    mode: 'history',
    scrollBehavior: () => ({ y: 0 }),
    routes: asyncRoutes
})
export default router

(2)新建一个公共的asyncRouter.js文件
// asyncRouter.js
//判断当前角色是否有访问权限
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
// 递归过滤异步路由表,筛选角色权限路由
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

(3)创建路由守卫:创建公共的permission.js文件,设置路由守卫
import router from './router'
import store from './store'
import NProgress from 'nprogress' // 进度条插件
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth' 
import { filterAsyncRoutes } from '@/utils/asyncRouter.js'

NProgress.configure({ showSpinner: false }) // 进度条配置

const whiteList = ['/login'] 

router.beforeEach(async (to, from, next) => {
    // 进度条开始
    NProgress.start()
     // 获取路由 meta 中的title,并设置给页面标题
    document.title = to.meta.title
    // 获取用户登录的token
    const hasToken = getToken()
    // 判断当前用户是否登录
    if (hasToken) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            // 从store中获取用户角色
            const hasRoles = store.getters.roles && store.getters.roles.length > 0  
            if (hasRoles) {
                next()
            } else {
                try {
                    // 获取用户角色
                    const roles = await store.state.roles
                    // 通过用户角色,获取到角色路由表
                    const accessRoutes = filterAsyncRoutes(await store.state.routers,roles)
                    // 动态添加路由到router内
                    router.addRoutes(accessRoutes)
                    next({ ...to, replace: true })
                } catch (error) {
                    // 清除用户登录信息后,回跳到登录页去
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        // 用户未登录
        if (whiteList.indexOf(to.path) !== -1) {
            // 需要跳转的路由是否是whiteList中的路由,若是,则直接条状
            next()
        } else {
            // 需要跳转的路由不是whiteList中的路由,直接跳转到登录页
            next(`/login?redirect=${to.path}`)
            // 结束精度条
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // 结束精度条
    NProgress.done()
})

(4)在main.js中引入permission.js文件
(5)在login登录的时候将roles存储到store中

2、复杂的路由权限设置(后端动态返回路由数据)

(1)配置项目路由文件,该文件中没有路由,或者存在一部分公共路由,即没有权限的路由

import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout';
Vue.use(Router)
// 配置项目中没有涉及权限的公共路由
export const constantRoutes = [
    {
        path: '/login',
        component: () => import('@/views/login'),
        hidden: true
    },
    {
        path: '/404',
        component: () => import('@/views/404'),
        hidden: true
    },
]

const createRouter = () => new Router({
    mode: 'history',
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})
const router = createRouter()

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}

export default router

(2)新建一个公共的asyncRouter.js文件
// 引入路由文件这种的公共路由
import { constantRoutes } from '../router';
// Layout 组件是项目中的主页面,切换路由时,仅切换Layout中的组件
import Layout from '@/layout';
export function getAsyncRoutes(routes) {
    const res = []
    // 定义路由中需要的自定名
    const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden']
    // 遍历路由数组去重组可用的路由
    routes.forEach(item => {
        const newItem = {};
        if (item.component) {
            // 判断 item.component 是否等于 'Layout',若是则直接替换成引入的 Layout 组件
            if (item.component === 'Layout') {
                newItem.component = Layout
            } else {
            //  item.component 不等于 'Layout',则说明它是组件路径地址,因此直接替换成路由引入的方法
                newItem.component = resolve => require([`@/views/${item.component}`],resolve)
                
                // 此处用reqiure比较好,import引入变量会有各种莫名的错误
                // newItem.component = (() => import(`@/views/${item.component}`));
            }
        }
        for (const key in item) {
            if (keys.includes(key)) {
                newItem[key] = item[key]
            }
        }
        // 若遍历的当前路由存在子路由,需要对子路由进行递归遍历
        if (newItem.children && newItem.children.length) {
            newItem.children = getAsyncRoutes(item.children)
        }
        res.push(newItem)
    })
    // 返回处理好且可用的路由数组
    return res
}

(3)创建路由守卫:创建公共的permission.js文件,设置路由守卫
//  进度条引入设置如上面第一种描述一样
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import { getAsyncRoutes } from '@/utils/asyncRouter'

const whiteList = ['/login'];
router.beforeEach( async (to, from, next) => {
    NProgress.start()
    document.title = to.meta.title;
    // 获取用户token,用来判断当前用户是否登录
    const hasToken = getToken()
    if (hasToken) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            //异步获取store中的路由
            let route = await store.state.addRoutes;
            const hasRouters = route && route.length>0;
            //判断store中是否有路由,若有,进行下一步
            if ( hasRouters ) {
                next()
            } else {
                //store中没有路由,则需要获取获取异步路由,并进行格式化处理
                try {
                    const accessRoutes = getAsyncRoutes(await store.state.addRoutes );
                    // 动态添加格式化过的路由
                    router.addRoutes(accessRoutes);
                    next({ ...to, replace: true })
                } catch (error) {
                    // Message.error('出错了')
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

(4)在main.js中引入permission.js文件
(5)在login登录的时候将路由信息存储到store中
//  登录接口调用后,调用路由接口,后端返回相应用户的路由res.router,我们需要存储到store中,方便其他地方拿取
this.$store.dispatch("addRoutes", res.router);

到这里,整个动态路由就可以走通了,但是页面跳转、路由守卫处理是异步的,会存在动态路由添加后跳转的是空白页面,这是因为路由在执行next()时,router里面的数据还不存在,此时,你可以通过window.location.reload()来刷新路由

后端返回的路由格式:

routerList = [
  {
        "path": "/other",
        "component": "Layout",
        "redirect": "noRedirect",
        "name": "otherPage",
        "meta": {
            "title": "测试",
        },
        "children": [
            {
                "path": "a",
                "component": "file/a",
                "name": "a",
                "meta": { "title": "a页面", "noCache": "true" }
            },
            {
                "path": "b",
                "component": "file/b",
                "name": "b",
                "meta": { "title": "b页面", "noCache": "true" }
            },
        ]
    }
]

注意:vue是单页面应用程序,所以页面一刷新数据部分数据也会跟着丢失,所以我们需要将store中的数据存储到本地,才能保证路由不丢失。关于vue页面刷新保存页面状态,可以查看 vue如何在页面刷新时保留状态信息

最后

公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西

有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭

  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现动态路由菜单,可以按照以下步骤进行: 1. 在路由配置文件中,定义一个需要动态生成的路由数组,如下所示: ``` const dynamicRoutes = [ { path: '/dashboard', name: 'Dashboard', component: () => import('@/views/dashboard'), meta: { title: 'Dashboard', icon: 'dashboard' } }, { path: '/user', name: 'User', component: () => import('@/views/user'), meta: { title: 'User', icon: 'user' }, children: [ { path: 'list', name: 'UserList', component: () => import('@/views/user/list'), meta: { title: 'User List', icon: 'user' } }, { path: 'detail/:id', name: 'UserDetail', component: () => import('@/views/user/detail'), meta: { title: 'User Detail', icon: 'user' } } ] } ] ``` 2. 在路由配置文件中,定义一个路由表,包含所有静态路由和需要动态生成的路由,如下所示: ``` import Vue from 'vue' import Router from 'vue-router' import staticRoutes from './staticRoutes' import dynamicRoutes from './dynamicRoutes' Vue.use(Router) const router = new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ ...staticRoutes, ...dynamicRoutes ] }) export default router ``` 3. 在菜单组件中,根据路由表动态生成菜单,如下所示: ``` <template> <el-menu :default-active="$route.path" class="el-menu-vertical-demo" :collapse="isCollapse"> <template v-for="item in menuList"> <template v-if="item.children"> <el-submenu :index="item.path"> <template slot="title"> <i :class="item.meta.icon"></i> <span slot="title">{{ item.meta.title }}</span> </template> <template v-for="child in item.children"> <el-menu-item :index="child.path" :key="child.path"> <router-link :to="child.path">{{ child.meta.title }}</router-link> </el-menu-item> </template> </el-submenu> </template> <template v-else> <el-menu-item :index="item.path" :key="item.path"> <i :class="item.meta.icon"></i> <router-link :to="item.path">{{ item.meta.title }}</router-link> </el-menu-item> </template> </template> </el-menu> </template> <script> export default { data() { return { menuList: [] } }, created() { this.menuList = this.$router.options.routes.filter(route => route.meta && route.meta.title) } } </script> ``` 其中,menuList 是根据路由表生成的菜单数组。在 created 钩子中,我们通过过滤路由表中有 meta.title 属性的路由,来生成菜单数组。 这样,就可以实现动态路由菜单了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值