最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • Vue的动态路由

    正文概述 掘金(马少钦)   2021-06-14   527

    最近为了加强学习,慢慢的研究一些模板,就比如 vue-element-admin模板。 这个模板写的非常好。里面也有一些难点,也是很好的一个学习方式让我们去学习。

    今天看到了的是 关于路由的动态管理的使用。以及webpack自动导入加载文件(控制加载和自动加载路由的动态管理: 先贴代码。 router中的index.js中的代码

    /**
     * 注意:子菜单仅在路由children.length> = 1时出现
     *
     * hidden: true                   如果设置true, 不会显示在侧边栏中(默认为false)
     * alwaysShow: true               如果设置true, 将始终显示根菜单
     *                                如果未设置alwaysShow,则当项有多个子路由时,
     *                                它将变为嵌套模式,否则不显示根菜单
     * Redirect: noRedirect           如果设置noRedirect,则不会在面包屑中重定向
     * name:'routerName'              用来使用<keep-alive>
     * meta : {
        title: 'title'                显示在侧边栏和面包屑的名称(推荐设置)
        icon: 'svg-name'              显示在侧边栏的icon
        noCache: true                 如果设置为true,将不缓存页面(默认为false)
        affix: true                   如果设置为true,则标签将固定在tags-view中
        breadcrumb: false             如果设置为false,在面包屑中不显示(默认为true)
        activeMenu: '/example/list'   如果设置了路径,则侧边栏将高亮显示所设置的路径
      }
     */
    
    /**
     * **constantRoutes**
     * 没有权限要求的基本页面
     * 所有角色都可以访问
     */
    export const constantRoutes = [
      {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
          {
            path: '/redirect/:path*',
            component: () => import('@/views/Redirect/index')
          }
        ]
      },
      {
        path: '/login',
        component: () => import('@/views/Login/index'),
        hidden: true
      },
      {
        path: '/404',
        component: () => import('@/views/404'),
        hidden: true
      },
      {
        path: '/',
        component: Layout,
        redirect: 'dashboard',
        children: [{
          path: 'dashboard',
          name: '首页',
          component: () => import('@/views/Dashboard'),
          meta: { title: '首页', icon: 'dashboard', affix: true }
        }]
      },
    
      {
        path: '/ad',
        component: Layout,
        name: 'Ad',
        redirect: '/ad/list',
        meta: { title: '广告管理', icon: 'ad' },
        children: [
          {
            path: 'list',
            component: () => import('@/views/Ad/List'),
            name: 'AdList',
            meta: { title: '广告管理', icon: 'ad' }
          }
        ]
      }
    ]
    
    /**
     * **asyncRoutes**
     * 需要根据后端返回的菜单列表动态匹配的路由
     */
    export const asyncRoutes = []
    
    const createRouter = () => new Router({
      // mode: 'history', // 需要后端支持
      scrollBehavior: () => ({ y: 0 }),
      routes: constantRoutes
    })
    
    const router = createRouter()
    
    // 动态重置路由
    export function resetRouter() {
      const newRouter = createRouter()
      router.matcher = newRouter.matcher // reset router
    }
    
    export default router
    

    根目录下建perssion.js目录

    import router from './router'
    import store from './store'
    import { Message } from 'element-ui'
    import NProgress from 'nprogress' // progress bar
    import 'nprogress/nprogress.css' // progress bar style
    import { getToken } from '@/utils/auth' // get token from cookie
    import getPageTitle from '@/utils/get-page-title'
    
    NProgress.configure({ showSpinner: false }) // NProgress Configuration
    
    /*
    配置好没有权限不允许进入的路由
      * */
    const whiteList = ['/login'] // no Redirect whitelist
    
    router.beforeEach(async(to, from, next) => {
      // start progress bar
      NProgress.start()
    
      // set page title
      document.title = getPageTitle(to.meta.title)
    
      // determine whether the user has logged in
      const hasToken = getToken()
      if (hasToken) {
        if (to.path === '/login') {
          // if is logged in, Redirect to the home page
          next({ path: '/' })
          NProgress.done()
        } else {
          const hasRoutes = store.getters.addRoutes && store.getters.addRoutes.length > 0
          if (hasRoutes) {
            next()
          } else {
            try {
              const menus = store.getters.menus
              const accessRoutes = await store.dispatch('permission/generateRoutes', menus)
              // 动态添加路由
              **router.addRoutes(accessRoutes)**
              // hack方法,以确保addRoutes是完整的
              // 设置replace:true,导航不会留下历史记录,因为如果addRouters还没执行完成,就next(),会出现白屏。如果...to,则会一直找到路径跳转.
              **next({ ...to, replace: true })**
            } catch (error) {
              // 删除token并进入登录页面重新登录
              await store.dispatch('user/resetToken')
              Message.error(error || 'Has Error')
              next(`/login?redirect=${to.path}`)
              NProgress.done()
            }
          }
        }
      } else {
        /* has no token*/
    
        if (whiteList.indexOf(to.path) !== -1) {
          // in the free login whitelist, go directly
          next()
        } else {
          // other pages that do not have permission to access are redirected to the login page.
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    })
    
    router.afterEach(() => {
      // finish progress bar
      NProgress.done()
    })
    
    

    store中的perssion.js

    import { asyncRoutes, constantRoutes } from '@/router'
    
    /**
     * @description 后端菜单匹配前端路由
     * @param {Array} menus 后端菜单
     * @param {Array} routers 前端路由
     * @returns {[]}
     */
    function dynamicRouter(menus, routers) {
      const res = []
      menus.forEach(temp => {
        const router = routers.find(router => temp.path === router.name)
        const accessedRouter = router && Object.assign({}, router)
        if (accessedRouter) {
          accessedRouter.meta.title = temp.name
          if (temp.children && temp.children.length > 0) {
            accessedRouter.children = dynamicRouter(temp.children, accessedRouter.children)
          }
          res.push(accessedRouter)
        }
      })
      return res
    }
    
    const state = {
      routes: [],
      addRoutes: []
    }
    
    const mutations = {
      SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
      }
    }
    
    const actions = {
      generateRoutes({ commit }, menus) {
        return new Promise(resolve => {
          const accessedRoutes = dynamicRouter(menus, asyncRoutes)
          // 404页必须放在最后!!!
          commit('SET_ROUTES', [...accessedRoutes, { path: '*', redirect: '/404', hidden: true }])
          resolve([...accessedRoutes, { path: '*', redirect: '/404', hidden: true }])
        })
      }
    }
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions
    }
    
    

    其实,在这,代码并不是重点。重点的是我们要理解这里面是如何运作的?如何在路由中搭配后端动态的给权限不同的人看到不同的界面和路由。 首先在router中的index.js中: 定义了所有人都能访问的路由,特别提醒:404页面一定要放在最后,因为*的通配符的优先级最低。也定义了根据权限的不同由后端访问不能的菜单目录。 **router.addRoutes(accessRoutes)**动态的添加后端返回来的路由进行连接。然后结合

      // 设置replace:true,导航不会留下历史记录,因为如果addRouters还没执行完成,就next(),会出现白屏。如果...to,则会一直找到路径跳转.
              **next({ ...to, replace: true })**
    

    这样我们就能根据不同的权限让后端返回不同的路由。 具体功能可以根据代码展示看看。

    谢谢


    起源地下载网 » Vue的动态路由

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元