vue权限页面控制

192 阅读1分钟

使用方式 router.addRouters()方法

1.定义页面时 将权限页面与普通页面
export const defaultRouter = []
export const appRouter = []
注册页面时先只注册defaultRouter
const router = new VueRouter({
    routes: defaultRouter
})
2.在守卫导航中通过接口获取权限页面
router.beforeEach((to,from,next) => {
    checkUser(next, to, router)
})
3.获取到权限页面后 从全部页面中过滤出来 添加到router中
  • 过滤菜单的方法
//routes 所有的页面 authPath 权限页面
const filterRouter = (routes, authPath) => {
  let res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (authPath[tmp.name] !== false) {
      if (tmp.children) {
        tmp.children = filterRouter(tmp.children, authPath)
      }
      res.push(tmp)
    }
  })
  return res
}
  • 添加到router中
router.addRoutes([...rawAppRouter])
4.其他补充点
  • location.href = location.origin跳转
5.核心代码
1.checkUser方法
export const checkUser = async (next, to, router) => {
  if (!store.getters.userInfo.userId) {
    try {
      let { authPath } = await store.dispatch('user/setUserInfo')
      let rawAppRouter = await store.dispatch('user/setAuth', authPath)
      let error404Page = { path: '/*', name: 'error-404', meta: { title: '404-页面不存在' }, component: () => import(`@/views/errorPage/404`) }
      router.addRoutes([...rawAppRouter, error404Page])
      let foundHomePages = findHomePage(rawAppRouter) // 查询子菜单所在的父级
      if (to.path === '/' && foundHomePages) {
        next({ ...foundHomePages, replace: true })
      } else {
        next({ ...to, replace: true })
      }
    } catch (e) {
      removeToken()
      location.href = location.origin
    }
  } else {
    next()
  }
}
// 查询路由首页
export const findHomePage = (router) => {
  let index = router.findIndex(el => el.children)
  if (!~index) return
  let result = router[index].children.find(el => el.meta && !el.meta.hideMenu && !el.meta.isLink)
  if (result || index >= router.length - 1) {
    return result
  } else {
    return findHomePage(router.slice(index + 1))
  }
}

2. 过滤
// 设置侧边权限菜单
setAuth ({ commit }, authPath) {
  return new Promise(resolve => {
    let rawAppRouter = filterRouter(appRouter, authPath)
    commit('SET_AUTH_MENU', rawAppRouter)
    resolve(rawAppRouter)
  })
}

// 过滤权限菜单
const filterRouter = (routes, authPath) => {
  let res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (authPath[tmp.name] !== false) {
      if (tmp.children) {
        tmp.children = filterRouter(tmp.children, authPath)
      }
      res.push(tmp)
    }
  })
  return res
}