IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> vue 动态路由实现 后端控制权限时的前端处理 -> 正文阅读

[JavaScript知识库]vue 动态路由实现 后端控制权限时的前端处理

前端思路:?

上图中?获取路由信息?,可以是后端控制的,可以是前端根据用户信息从路由表中筛选的。

此处讲解后端存储路由信息的情况

组织路由信息

请求后台,获取返回结果,结果有两种可能,一种是组合好的树状结构,一种是路由平铺

树状结构:

不需要重组路由结构,但是需要替换组件信息

import components from '@/router/components'

/* 遍历后台传来的路由字符串,转换为组件对象
 * @params asyncRouterMap MyRoute[] 异步路由数组
 * @params type boolean 是否需要重写子路由路径
*/
function filterAsyncRouter(asyncRouterMap: MyRoute[], type = false) {
  return asyncRouterMap.filter(route => {

    if (type && route.children) {
      route.children = rewriteChildrenPath(route.children, route)
    }
    if (route.component) {
      // 如果路径组件在路由表中查询不到,默认渲染NotFound组件,其他情况可自定义处理
      if (!Object.keys(components).includes(route.component as string)) {
        route.component = components.NotFound
      } else {
        route.component = components[route.component as keyof typeof components]
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, type)
    } else {
      delete route[`children`]
      delete route[`redirect`]
    }
    return true
  })
}

/* 重写路由中子路由路径
 * @params childernMap MyRoute[] 子路由数组信息
 * @params lastRouter MyRoute 父路由信息
*/
function rewriteChildrenPath(childrenMap: MyRoute[], lastRouter: MyRoute) {
  let children: MyRoute[] = []
  childrenMap.forEach((el) => {
    el.path = `${lastRouter.path }/${ el.path}`
    children = children.concat(el)
  })
  return children
}

?路由平铺

此时除了替换组件信息,还需要构建树状路由结构

let routes = res.map(organizeRoute) //organizeMenu 工具函数 重组路由结构
routes = recursiveData(routes, ``)

import Components from '@/routers/component'

// 菜单组织为route形式
const organizeRoute= (route) => {
  // 防止顶级路由未加斜杠报错
  const path = route.path.indexOf(`/`) !== 0 ? `/${route.path}` : route.path
  const _route= {
    //...符合route的属性和其他自定义属性
    component: route.component && Components[route.component] || Components.NotFound,
    meta: {
      title: route.title,
      hidden: route.hidden,
      icon: route.icon,
      //...其他自定义属性
    },
    query: {},
    params: {},
  }
  // 重定向
  route.redirect && Object.assign(_route, { redirect: { name: route.redirect } })
  return _route
}


//重组树状路由结构
const organizeRouteTree= (routes, pid = `0`) => {
  const _routes= routes.filter(item => item.pid === pid) //找出所有父级路由

  if (!_routes|| _routes.length === 0) return []

  _routes.sort((prev, next) => {
    return prev.sort - next.sort
  })
  _routes.map(item => {
    const children = organizeRouteTree(routes, item.id)
    children && children.length > 0 && (item.children = children)
  })
  return _routes
}

动态加到路由表

路由守卫中动态添加

//获取用户信息
userStore.getUserInfo()
  .then(() => {
    //isRelogin.show = false
    perssionStore.getRoutes()
      .then(accessRoutes => { //accessRoutes上一步中处理好的树状路由信息
        accessRoutes.forEach(route => {
          if (!isHttp(route.path)) {
            router.addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
          }
        })
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
      })
  })
  .catch(err => {
    userStore.logOut()
      .then(() => {
        notification.error({
          message: err.code,
          description: err.message || err.msg,
        })
        next({ path: `/` })
      })
  })


/**
 * 判断url是否是http或https
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url:string) {
  return url.indexOf(`http://`) !== -1 || url.indexOf(`https://`) !== -1
}

非路由守卫中添加?

const createRouter = (routes = []) => {
? const _routes = [...baseRoutes, ...routes]
? return new Router({
? ? mode: `hash`,
? ? routes: _routes,
? ? scrollBehavior: () => ({ y: 0 }),
? })
}

const router = createRouter()

export function resetRouter (routes = []) {
? const newRouter = createRouter(routes)
? router.matcher = newRouter.matcher // the relevant part
}

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2022-09-21 00:19:29  更:2022-09-21 00:20:44 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年9日历 -2024/9/17 4:03:26-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码