vue-admin-template 动态路由的实现(方式一)

这里只是一个demo,后台返回的路由数据可能不太规范,这里是手动强制修改的,正式线保持一致

  • 首先改造router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * constantRoutes
 * 所有的页面必须在这里进行挂载
 * all roles can be accessed
 */

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

/**
 * 放置通用所有人都可以用的路由
 */
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

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

  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
      path: 'home',
      name: 'Home',
      component: () => import('@/views/home/index'),
      meta: { title: 'AI业务培训管理系统', icon: '' }
    }]
  },

  {
    path: '/addrole',
    hidden: true,
    component: Layout,
    children: [
      {
        path: 'index/:id',
        name: 'Addrole',
        component: () => import('@/views/usermanage/addrole/index'),
        meta: { title: '添加角色', icon: '' }
      }
    ]
  },
  {
    path: '/addaccount',
    hidden: true,
    component: Layout,
    children: [
      {
        path: 'index/:id',
        name: 'AddAccount',
        component: () => import('@/views/usermanage/addaccount/index'),
        meta: { title: '添加账户', icon: '' }
      }
    ]
  },
  {
    path: '/addbanner',
    hidden: true,
    component: Layout,
    children: [
      {
        path: 'index/:id',
        name: 'AddBanner',
        component: () => import('@/views/appmanage/addbanner/index'),
        meta: { title: '添加Banner', icon: '' }
      }
    ]
  },
  {
    path: '/createactivationcode',
    hidden: true,
    component: Layout,
    children: [
      {
        path: 'index',
        name: 'CreateActivationCode',
        component: () => import('@/views/vipmanage/createactivationcode/index'),
        meta: { title: '生成激活码', icon: '' }
      }
    ]
  },
]
/**
 * 放置服务器可配置的动态路由
 */
export const asyncRoutes = [
  {
    path: '/usermanagement',
    component: Layout,
    redirect: '/usermanagement/rolemanagement',
    meta: { title: '用户管理', icon: 'user' },
    children: [
      {
        path: 'rolemanagement',
        component: () => import('@/views/usermanage/rolemanagement/index'),
        meta: { title: '角色管理', icon: '' }
      },
      {
        path: 'accountlist',
        component: () => import('@/views/usermanage/accountlist/index'),
        meta: { title: '账号列表', icon: '' }
      }
    ]
  },
  {
    path: '/voicemanage',
    component: Layout,
    redirect: '/voicemanage/albumscategories',
    meta: { title: '语音管理', icon: 'voice' },
    children: [
      {
        path: 'albumscategories',
        component: () => import('@/views/voicemanage/albumscategories/index'),
        meta: { title: '专辑分类', icon: '' }
      },
      {
        path: 'listenmanage',
        component: () => import('@/views/voicemanage/listenmanage/index'),
        meta: { title: '收听管理', icon: '' }
      }
    ]
  },
  {
    path: '/appmanagement',
    component: Layout,
    redirect: '/appmanagement/banner',
    meta: { title: 'App管理', icon: 'app' },
    children: [
      {
        path: 'banner',
        component: () => import('@/views/appmanage/banner/index'),
        meta: { title: 'Banner管理', icon: '' }
      },
      {
        path: 'appversions',
        component: () => import('@/views/appmanage/appversions/index'),
        meta: { title: 'App版本管理', icon: '' }
      }
    ]
  },
  {
    path: '/vipmanagement',
    component: Layout,
    redirect: '/vipmanagement/setmeal',
    meta: { title: 'VIP管理', icon: 'vip' },
    children: [
      {
        path: 'setmeal',
        component: () => import('@/views/vipmanage/setmeal/index'),
        meta: { title: '套餐管理', icon: '' }
      },
      {
        path: 'activationcode',
        component: () => import('@/views/vipmanage/activationcode/index'),
        meta: { title: '激活码管理', icon: '' }
      },
      {
        path: 'activationcodelist',
        component: () => import('@/views/vipmanage/activationcodelist/index'),
        meta: { title: '激活码生成列表', icon: '' }
      },
      {
        path: 'activationcodeexport',
        component: () => import('@/views/vipmanage/activationcodeexport/index'),
        meta: { title: '激活码导出列表', icon: '' }
      },
      {
        path: 'orderlist',
        component: () => import('@/views/vipmanage/orderlist/index'),
        meta: { title: '订单列表', icon: '' }
      },
      {
        path: 'vipequity',
        component: () => import('@/views/vipmanage/vipequity/index'),
        meta: { title: 'VIP权益说明', icon: '' }
      }
    ]
  },
  {
    path: '/brandownermanage',
    component: Layout,
    redirect: '/brandownermanage/brandownerlist',
    alwaysShow: true,
    meta: { title: '品牌商管理', icon: 'brand' },
    children: [
      {
        path: 'brandownerlist',
        component: () => import('@/views/brandownermanage/brandownerlist/index'),
        meta: { title: '品牌商列表', icon: '' }
      }
    ]
  },
  {
    path: '/machinemanage',
    component: Layout,
    redirect: '/machinemanage/machinelist',
    alwaysShow: true,
    meta: { title: '机器管理', icon: 'android' },
    children: [
      {
        path: 'machinelist',
        component: () => import('@/views/machinemanage/machinelist/index'),
        meta: { title: '机器列表', icon: '' }
      }
    ]
  },
  {
    path: '/softwaremanage',
    component: Layout,
    redirect: '/softwaremanage/versions',
    meta: { title: '软件管理', icon: 'software' },
    children: [
      {
        path: 'versions',
        component: () => import('@/views/softwaremanage/versions/index'),
        meta: { title: '版本管理', icon: '' }
      },
      {
        path: 'usedirection',
        component: () => import('@/views/softwaremanage/usedirection/index'),
        meta: { title: '使用说明', icon: '' }
      }
    ]
  },
  {
    path: '/officialaccounts',
    component: Layout,
    redirect: '/officialaccounts/accesssettings',
    meta: { title: '公众号设置', icon: 'weichat' },
    children: [
      {
        path: 'accesssettings',
        component: () => import('@/views/officialaccounts/accesssettings/index'),
        meta: { title: '接入设置', icon: '' }
      },
      {
        path: 'menu',
        component: () => import('@/views/officialaccounts/menu/index'),
        meta: { title: '菜单设置', icon: '' }
      },
      {
        path: 'attentionreply',
        component: () => import('@/views/officialaccounts/attentionreply/index'),
        meta: { title: '关注回复', icon: '' }
      },
      {
        path: 'keywordreply',
        component: () => import('@/views/officialaccounts/keywordreply/index'),
        meta: { title: '关键字回复', icon: '' }
      },
      {
        path: 'material',
        component: () => import('@/views/officialaccounts/material/index'),
        meta: { title: '素材管理', icon: '' }
      }
    ]
  },
]


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

export 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
  • 获取动态路由数据api/user.js
import request from '@/utils/request'
import qs from 'qs'

/**
 *动态路由
 */
export function getAuthMenu() {
  return request({
    url: '/Admin/Index',
    method: 'get'
  })
}


  • 修改权限规则(store/module/permission.js)

vue-admin-template模板本身是没有做权限的,自己创建一个即可,规则自己设定,admin中使用的roles配置的,我这里是自动生成的,本质还是生成新的路由list(只是包含新的路由)

注意:store/module/permission.js和项目根目录下的permission别搞混了

import { asyncRoutes, constantRoutes, errorRoutes } from '@/router'
import { getAuthMenu } from '@/api/user'
import Layout from '@/layout'
import { Message } from "element-ui"



/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * 这里是demo使用的是以前项目的后台数据,这里强制修改了一下
 * @param routes
 */
export function generaMenu(routes, data, parent) {
  data.forEach(item => {
    let menu
    let viewpath
    if (parent == "/usermanagement") {
      viewpath = "/usermanage"
    } else if (parent == "/appmanagement") {
      viewpath = "/appmanage"
    } else if (parent == "/vipmanagement") {
      viewpath = "/vipmanage"
    } else {
      viewpath = parent
    }
    if (parent === '#') {
      menu = {
        path: item.path,
        component: Layout,
        children: [],
        redirect: `${item.path}/${item.children[0].path}`,
        meta: { title: item.name, icon: item.icon }
      }
    } else {
      menu = {
        path: item.path,
        component: loadView(viewpath, item.path),
        children: [],
        name: item.path,
        meta: { title: item.name }
      }
    }
    if (item.children) {
      generaMenu(menu.children, item.children, item.path)
    }
    routes.push(menu)
  })
}

export const loadView = (parent, path) => { // 路由懒加载
  return (resolve) => require([`@/views${parent}/${path}/index`], resolve)
  // return () => import(`@/views${parent}/${path}/index`)
}

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.code !== 200) {
          Message({
            message: "菜单数据加载异常",
            type: 0,
            duration: 2 * 1000
          });
        } else {
          let data = response.data.menu_list
          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
}


  • 配置项目根目录下的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

//动态路由添加'/auth-redirect'
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 hasGetUserInfo = store.getters.name
      //动态路由
      const hasGetUserInfo = store.getters.name&&store.getters.permission_routes.length > 0
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          // await store.dispatch('user/getInfo')
          // next()

          //配置动态路由
          const { contact_name } = await store.dispatch('user/getInfo')
          const accessRoutes = await store.dispatch('permission/generateRoutes', contact_name)
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          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/getters.js中添加 permission_routes

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,
  language:state=>state.app.language,
  //动态路由
  permission_routes: state => state.permission.routes,
}
export default getters

  • 将数据绑定到nav导航栏上

    在layout/components/sidebar/index.vue中

...mapGetters([
      // 动态路由 增加permission_routes
      'permission_routes',
      'sidebar'
    ]),

 <!-- 动态路由 -->
 <sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />
      
全部代码如下:
<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"
      >
        <!-- 所有路由 -->
        <!-- <sidebar-item v-for="route in routes" :key="route.path" :item="route" :base-path="route.path" /> -->
        <!-- 动态路由 -->
        <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
      '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>

  • 效果

在这里插入图片描述
完成

©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页