vue-admin-template 动态路由

采用的是 vue-admin-template 后台管理系统模板,大家耐心看完绝对就能解决动态路由了

1、首先在 router>index.js下面的内容,这部分倒是没有什么特别大的改动:

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)



/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  }

]
/**
 * asyncRoutes
 * the routes that need to be dynamically loaded based on user roles
 */
export const asyncRoutes = [
]

export const errorRoutes = [
  // 404 页面必须放置在最后一个页面
  { path: '*', redirect: '/404', hidden: true }
]



const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})



const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

2、然后根据后端返回的路由来拼接路由,这里我给大家展示一下,数据有所差异。在 store>modules>permission.js,如果没有就创建一个:

import { asyncRoutes, constantRoutes,errorRoutes } from '@/router';
import { getAuthMenu } from '@/api/menuRouter';//这是请求后端的路由接口
import Layout from '@/layout'
import {asnycRouteMeun} from "@/router/modules/asnycRoute.js";//这里是引入模块组件,因为动态生成路由的话不支持 => 所以我们可以写在外部

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * 这里是demo使用的是以前项目的后台数据,这里强制修改了一下
 * @param routes
 */
export function generaMenu(routes,data) {
  data.forEach(item => {
    let menu
    let viewpath
    if (item.sub.length==0) {
      const component = item.route? asnycRouteMeun[`${item.route}`] : Layout;
      menu = {
        path: `${item.route_path}`,
        component: Layout,
        children: [
          {
            path: `index`,
            name: `${item.route_name}`,
            meta: { title: `${item.name}`}
          }
        ]
      }
      if(item.route){
        menu.children[0].component = component;
      }
    } else {
      let menuSub=[];
      // console.log(asnycRouteMeun["clientManagement"],'asnycRouteMeun')
      for(let itemIn of item.sub){
        const component = itemIn.route? asnycRouteMeun[`${itemIn.route}`] : Layout;
        let obj = {
          path:`${itemIn.route_path}`,
          component,
          name: `${itemIn.route_name}`,
          meta: { title:`${itemIn.name}`,icon:`${itemIn.icon}` }
        }
        if(itemIn.hidden == 'true'){
          obj.hidden = true;
        }
        menuSub.push(obj)
      }
      menu = {
        path: `${item.route_path}`,
        component: Layout,
        children: [].concat(menuSub),
        redirect: `${item.route_path}/${item.sub[0].route_path}`,
        name: `${item.route_name}`,
        meta: { title: `${item.name}` }
      }
    }
    routes.push(menu)
  })
}

export const loadView = (path) => { // 路由懒加载
  // return (resolve) => require(`${path}`)
  return () => import(`${path}`)
}


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
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
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes).concat(errorRoutes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      getAuthMenu().then(response => {
        if (response.status !== 200) {
          Message({
            message: "菜单数据加载异常",
            type: 0,
            duration: 2 * 1000
          });
        } else {
          let data = response.data.data
          Object.assign(loadMenuData, data);
          let routes=[]
          generaMenu(routes,loadMenuData)
          let accessedRoutes
          // if (roles.includes('admin')) {
          //   accessedRoutes = asyncRoutes || []
          // } else {
            accessedRoutes = routes
          // }
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
      }).catch(error => {
        console.log(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

注意 store 里面的文件必须要在 store>index.js 里面创建:

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import permission from './modules/permission'//这是引入我们创建的那个文件,

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user,
    permission//这里注册一下
  },
  getters
})

export default store

3、在那个 store>modules>permission.js 里面引入的 import {asnycRouteMeun} from “@/router/modules/asnycRoute.js”;:

/**
 * 动态路由配置,需要权限
 */
export const asnycRouteMeun = {
  "monitoringIndex": () => import('@/views/monitoringIndex/index'),
  "clientMonitoring": () => import('@/views/clientMonitoring/index'),
  "resourceAdministration": () => import('@/views/resourceAdministration/index'),
  "clientManagement": () => import('@/views/clientManagement/index'),
  "cloudServer": () => import('@/views/cloudServer/index'),
  "cloudSwitches": () => import('@/views/cloudSwitches/index'),
  "cloudEdit": () => import('@/views/cloudServer/edit'),
}

4、成功之后可以看看 src>permission.js 注意不要跟 store 里面的 permission.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', '/auth-redirect'] // 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() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.name&&store.getters.permission_routes.length > 0;
      // console.log(store.getters.permission_routes,'store.gettersstore.getters');
      // console.log(to.path,hasRoles,'to.path')
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          // dynamically add accessible routes
          // console.log(accessRoutes,'accessRoutes')
          // 把404放后面,不然会一直报404
          router.addRoutes([...accessRoutes, { path: '*', redirect: '/404', hidden: true }])
          //这里可以打印出来看一下动态路由格式是否正确
          // console.log(accessRoutes,'accessRoutes===')
          // hack method  to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          // console.log(accessRoutes,'to');
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          // console.log(error)
          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()
})

5、如果正确的话,请注意这里 src>layout>components>sidebar>index.vue :

<template>
  <div :class="{'has-logo':showLogo}">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
      >
      //这里需要的是填写你动态生成后的路由,不再是之前的router,只需要改v-for 距离路由怎么拼接的,想了解的可以去看 sidebarItem 它这个组件 这里改了 下面 computed 里面还有改一下
        <sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'

export default {
  components: { SidebarItem, Logo },
  computed: {
  //把这里改成这种
    ...mapGetters(['permission_routes',
      'sidebar'
    ]),
    routes() {
      return this.$router.options.routes
    },
    activeMenu() {
      const route = this.$route
      const { meta, path } = route
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu
      }
      return path
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo
    },
    variables() {
      return variables
    },
    isCollapse() {
      return !this.sidebar.opened
    }
  }
}
</script>

6、这里之后还不能成功 ,还要去 store>getters.js 里面:

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
   //动态路由 ,这里需要设置一下
   permission_routes: state => state.permission.routes
}
export default getters

7、这是我生成后的路由
在这里插入图片描述
总结:总的来说动态路由需要注意的地方比较多,最主要就是后端返回的数据 我们要拼接对,这个可以打印出来看,只要生成没问题,后面就是 添加路由然后挂上去就完了,希望对大家有帮助,毕竟我之前写的时候也是看了文章这些,但是我觉得都只是写了一部分,害我走了好多坑 哈哈哈

Logo

前往低代码交流专区

更多推荐