vue 后台權限控制多級(3級別路由)路由實現思路


這篇文章主要介紹了Vue 權限控制的兩種方法(路由驗證),每種方法給大家介紹的非常詳細,具有一定的參考借鑒價值

實現思路

1、登陸 獲得token

    @Action({ rawError: true })
    public async Login(userInfo: { username: string, password: string, captcha: string }) {
        let { username, password, captcha } = userInfo
        username = username.trim()
        const { data } = await login({ username, password, captcha })
        setToken(data.token)
        this.SET_TOKEN(data.token)
    }

2、攜帶token獲取用戶的信息和菜單權限

@Action
    public async GetUserInfo() {
        if (this.token === '') {
            throw Error('GetUserInfo: token is undefined!')
        }
        const { data } = await getUserInfo({ /* Your params here */ })
        if (!data) {
            throw Error('驗證失敗請重新登陸.')
        }
        const { roles, nickname, avatar, menus } = data
      
        if (!roles || roles.length <= 0) {
            throw Error('GetUserInfo: roles must be a non-null array!')
        }
        if (menus) {
            this.SET_MENU(menus)
        }
        const avatarUrl = avatar === null ? 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80' : avatar
        this.SET_AVATAR(avatarUrl)
        this.SET_ROLES([...roles, 'admin'])
        this.SET_NAME(nickname)
    }

3、獲取到的菜單動態生成路由對象routes

const getSecMenuList = (childrenRouter: any) => {
    const secAuthorityList: Array<RouteConfig> = []
    for (let k = 0; k < childrenRouter.length; k++) {
        const secItems = childrenRouter[k]
        secAuthorityList.push({
            path: secItems.router,
            component: loadView(secItems.path),
            name: secItems.name,
            meta: {
                title: secItems.name,
                icon: 'dashboard',
                roles: ['admin'],
                noCache: true
            },
            children: secItems.children.length > 0 ? getthMenuList(secItems.children) : undefined
        })
    }
    return secAuthorityList
}

4、用vue提供的addRouter(...routes) 吧動態的路由合並到原始的路由對象上。

router.addRoutes(this.dynamicRoutes)

5、把動態生成的路由對象和原始的router.options.routes對象實例進行合並。

router.options.routes = router.options.routes?.concat(this.dynamicRoutes)

整體代碼實現

@Action({ rawError: true })
    public async GetRemoteRouter() {
        const adminAuthority = await getMenusList(UserModule.menus)
        this.SET_ROUTES(adminAuthority)
        router.addRoutes(this.dynamicRoutes)
        router.options.routes = router.options.routes?.concat(this.dynamicRoutes)
    }

Vue 動態加載組件的四種方式

使用import導入組件,可以獲取到組件

const loadView(view:any){
      return () =>  import(`../components/${view}`)
}

使用import導入組件,直接將組件賦值給componet

var route={
  name:name,
  component : () => import(`../components/${name}`)
}

使用require 導入組件,直接將組件賦值給componet

第一種 使用 require.ensure([],resolve(''))

const loadView(view:any){
     return (resolve:any) => require.ensure([], () => resolve(require(`../components/${view}`)))
}

第二種 使用 (resolve) => require([...url],resolve)

const loadView(view:any){
     return (resolve:any) => require([`../components/${view}`], resolve)
}

第三種 使用 require('url').default

const loadView(view:any){
     return require(`../components/${view}`).default
}

1、三級以上的路由 也是需要給組件的 路由里面放<router-view></router-view>

2、這里我在做的時候踩了坑,當時routes目錄對象里面沒有給component ,結果子路由就沒辦法顯示。后來加了一個組件就可以了。

3、后來總結了下。路由routes里面凡事遇到大於二級的。即children個數大於二的。都需要給路由容器,不然自路由沒有辦法顯示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM