站長資訊網
最全最豐富的資訊網站

vue動態路由有哪兩種實現方法

vue動態路由的兩種實現方法:1、簡單的角色路由設置,比如只涉及到管理員和普通用戶的權限;通常直接在前端進行簡單的角色權限設置。2、復雜的路由權限設置,比如OA系統、多種角色的權限配置;通常需要后端返回路由列表,前端渲染使用。

vue動態路由有哪兩種實現方法

本教程操作環境:windows7系統、vue3版,DELL G3電腦。

動態路由不同于常見的靜態路由,可以根據不同的「因素」而改變站點路由列表。

動態路由設置一般有兩種:

(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 defaultRouter = [{     path: '/404',     name: '404',     component: () => import('@/views/404'),      meta: {         title: '404'     } }] let router = new Router({     mode: 'history',     scrollBehavior: () => ({ y: 0 }),     routes: defaultRouter }) 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中的數據存儲到本地,才能保證路由不丟失。

贊(0)
分享到: 更多 (0)
網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
国产精品视频白浆免费视频| 久久se这里只有精品| 久久久这里只有精品加勒比| 国产l精品国产亚洲区在线观看| 国产网红主播无码精品| 日韩AV无码精品一二三区| 男人扒开女人下添高潮日韩视频| 成人无码精品一区二区三区| 免费精品国产日韩热久久| 91精品在线国产| 99热在线精品播放| 久久精品成人无码观看56| 日韩精品人妻一区二区中文八零| 国产精品夜色视频一级区| 七次郎在线视频精品视频| 亚洲日韩国产欧美一区二区三区| 日韩精品一区二区三区不卡| 精品国产夜色在线| 国产精品久久久久久精品三级| www.国产精品.com| 国产精品久久久久久久app| 国产精品91在线| 久9视频这里只有精品| 亚洲精品视频久久| 91精品免费久久久久久久久| 69p69国产精品| 91精品视频观看| 国产精品久久久久无码av| 亚洲av永久无码精品三区在线4| 亚洲精品自拍视频| 国产精品久久久久久| 99精品无人区乱码在线观看| 国产精品55夜色66夜色| 国产精品久久99| 无码精品A∨在线观看十八禁| 免费精品国产自产拍在线观看图片| 波多野结衣久久精品| 国产精品嫩草影院AV| 精品久久久久久亚洲综合网| 国产精品一区二区电影| 日韩精品免费一线在线观看|