溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue動(dòng)態(tài)路由的實(shí)現(xiàn)方法有哪些

發(fā)布時(shí)間:2022-12-27 09:09:52 來源:億速云 閱讀:151 作者:iii 欄目:web開發(fā)

本篇內(nèi)容介紹了“vue動(dòng)態(tài)路由的實(shí)現(xiàn)方法有哪些”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

vue動(dòng)態(tài)路由的兩種實(shí)現(xiàn)方法:1、簡(jiǎn)單的角色路由設(shè)置,比如只涉及到管理員和普通用戶的權(quán)限;通常直接在前端進(jìn)行簡(jiǎn)單的角色權(quán)限設(shè)置。2、復(fù)雜的路由權(quán)限設(shè)置,比如OA系統(tǒng)、多種角色的權(quán)限配置;通常需要后端返回路由列表,前端渲染使用。

動(dòng)態(tài)路由不同于常見的靜態(tài)路由,可以根據(jù)不同的「因素」而改變站點(diǎn)路由列表。

動(dòng)態(tài)路由設(shè)置一般有兩種:

(1)、簡(jiǎn)單的角色路由設(shè)置:比如只涉及到管理員和普通用戶的權(quán)限。通常直接在前端進(jìn)行簡(jiǎn)單的角色權(quán)限設(shè)置

(2)、復(fù)雜的路由權(quán)限設(shè)置:比如OA系統(tǒng)、多種角色的權(quán)限配置。通常需要后端返回路由列表,前端渲染使用

1、簡(jiǎn)單的角色路由設(shè)置

(1)配置項(xiàng)目路由權(quán)限

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
Vue.use(Router)// 權(quán)限路由列表
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角色的用戶才能訪問該頁(yè)面
                }
            },
            {
                path: 'role',
                component: () => import('@/views/permission/role'),
                name: 'RolePermission',
                meta: {
                    title: 'Role',
                    roles: ['admin']    //  admin角色的用戶才能訪問該頁(yè)面
                }
            }
        ]
    },
 ]
 // 靜態(tài)路由
 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)新建一個(gè)公共的asyncRouter.js文件

// asyncRouter.js
//判斷當(dāng)前角色是否有訪問權(quán)限
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 遞歸過濾異步路由表,篩選角色權(quán)限路由
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)創(chuàng)建路由守衛(wèi):創(chuàng)建公共的permission.js文件,設(shè)置路由守衛(wèi)

import router from './router'
import store from './store'
import NProgress from 'nprogress' // 進(jìn)度條插件
import 'nprogress/nprogress.css' // 進(jìn)度條樣式
import { getToken } from '@/utils/auth' 
import { filterAsyncRoutes } from '@/utils/asyncRouter.js'
NProgress.configure({ showSpinner: false }) // 進(jìn)度條配置
const whiteList = ['/login'] 
router.beforeEach(async (to, from, next) => {
    // 進(jìn)度條開始
    NProgress.start()
     // 獲取路由 meta 中的title,并設(shè)置給頁(yè)面標(biāo)題
    document.title = to.meta.title    // 獲取用戶登錄的token
    const hasToken = getToken()
    // 判斷當(dāng)前用戶是否登錄
    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)
                    // 動(dòng)態(tài)添加路由到router內(nèi)
                    router.addRoutes(accessRoutes)
                    next({ ...to, replace: true })
                } catch (error) {
                    // 清除用戶登錄信息后,回跳到登錄頁(yè)去
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        // 用戶未登錄
        if (whiteList.indexOf(to.path) !== -1) {
            // 需要跳轉(zhuǎn)的路由是否是whiteList中的路由,若是,則直接條狀
            next()
        } else {
            // 需要跳轉(zhuǎn)的路由不是whiteList中的路由,直接跳轉(zhuǎn)到登錄頁(yè)
            next(`/login?redirect=${to.path}`)
            // 結(jié)束精度條
            NProgress.done()
        }
    }})
    router.afterEach(() => {
    // 結(jié)束精度條
    NProgress.done()
   })

(4)在main.js中引入permission.js文件

(5)在login登錄的時(shí)候?qū)oles存儲(chǔ)到store中

2、復(fù)雜的路由權(quán)限設(shè)置(后端動(dòng)態(tài)返回路由數(shù)據(jù))

(1)配置項(xiàng)目路由文件,該文件中沒有路由,或者存在一部分公共路由,即沒有權(quán)限的路由

import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout';
Vue.use(Router)// 配置項(xiàng)目中沒有涉及權(quán)限的公共路由
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)新建一個(gè)公共的asyncRouter.js文件

// 引入路由文件這種的公共路由
import { constantRoutes } from '../router';// Layout 組件是項(xiàng)目中的主頁(yè)面,切換路由時(shí),僅切換Layout中的組件
import Layout from '@/layout';
export function getAsyncRoutes(routes) {
    const res = []
    // 定義路由中需要的自定名
    const keys = ['path', 'name', 'children', 'redirect', 'meta', 'hidden']
    // 遍歷路由數(shù)組去重組可用的路由
    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引入變量會(huì)有各種莫名的錯(cuò)誤
                // newItem.component = (() => import(`@/views/${item.component}`));
            }
        }
        for (const key in item) {
            if (keys.includes(key)) {
                newItem[key] = item[key]
            }
        }
        // 若遍歷的當(dāng)前路由存在子路由,需要對(duì)子路由進(jìn)行遞歸遍歷
        if (newItem.children && newItem.children.length) {
            newItem.children = getAsyncRoutes(item.children)
        }
        res.push(newItem)
    })
    // 返回處理好且可用的路由數(shù)組
    return res
 }

(3)創(chuàng)建路由守衛(wèi):創(chuàng)建公共的permission.js文件,設(shè)置路由守衛(wèi)

//  進(jìn)度條引入設(shè)置如上面第一種描述一樣
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,用來判斷當(dāng)前用戶是否登錄
    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中是否有路由,若有,進(jìn)行下一步
            if ( hasRouters ) {
                next()
            } else {
                //store中沒有路由,則需要獲取獲取異步路由,并進(jìn)行格式化處理
                try {
                    const accessRoutes = getAsyncRoutes(await store.state.addRoutes );
                    // 動(dòng)態(tài)添加格式化過的路由
                    router.addRoutes(accessRoutes);
                    next({ ...to, replace: true })
                } catch (error) {
                    // Message.error('出錯(cuò)了')
                    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登錄的時(shí)候?qū)⒙酚尚畔⒋鎯?chǔ)到store中

//  登錄接口調(diào)用后,調(diào)用路由接口,后端返回相應(yīng)用戶的路由res.router,我們需要存儲(chǔ)到store中,方便其他地方拿取
this.$store.dispatch("addRoutes", res.router);

到這里,整個(gè)動(dòng)態(tài)路由就可以走通了,但是頁(yè)面跳轉(zhuǎn)、路由守衛(wèi)處理是異步的,會(huì)存在動(dòng)態(tài)路由添加后跳轉(zhuǎn)的是空白頁(yè)面,這是因?yàn)槁酚稍趫?zhí)行next()時(shí),router里面的數(shù)據(jù)還不存在,此時(shí),你可以通過window.location.reload()來刷新路由
后端返回的路由格式:

routerList = [
  {
        "path": "/other",
        "component": "Layout",
        "redirect": "noRedirect",
        "name": "otherPage",
        "meta": {
            "title": "測(cè)試",
        },
        "children": [
            {
                "path": "a",
                "component": "file/a",
                "name": "a",
                "meta": { "title": "a頁(yè)面", "noCache": "true" }
            },
            {
                "path": "b",
                "component": "file/b",
                "name": "b",
                "meta": { "title": "b頁(yè)面", "noCache": "true" }
            },
        ]
    }
]

注意:vue是單頁(yè)面應(yīng)用程序,所以頁(yè)面一刷新數(shù)據(jù)部分?jǐn)?shù)據(jù)也會(huì)跟著丟失,所以我們需要將store中的數(shù)據(jù)存儲(chǔ)到本地,才能保證路由不丟失。

“vue動(dòng)態(tài)路由的實(shí)現(xiàn)方法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI