vue-admin-template 动态路由步骤

api/user.js存放接口

import request from '@/utils/request'
// 登录
export function login(data) {
     
  return request({
     
    url: '/auth',
    method: 'post',
    data
  })
}
// 用户信息
export function getInfo(token) {
     
  return request({
     
    url: '/api/v1/userInfo',
    method: 'get',
    params: {
      token }
  })
}
// 退出
export function logout() {
     
  return request({
     
    url: '/logout',
    method: 'GET'
  })
}

// 登录接口返回数据

{
     "code":200,"data":{
     "token":"eyJhbGciOiJIUzI1NiIsInR5...mdOL7Tjkqc-sY","type":"Bearer","user_info":{
     "role":[],"user_id":1,"username":"admin"}},"msg":"ok"}

// 用户信息接口返回数据 userinfo

{
     "code":200,"data":{
     "company":" ","department":" ","department_big":" ","mobile":"15625053620","permissions":["/shezhi","","jurisdiction","/friends","management","weifenpei","/call","/sensSetting","personal","dashboard","yuangong","callrecords","callvoice","allfriends","behavior","behavior_shezhi","mobile_sms","/statistical","totaltable","trendwechat","wxstatistics","callstatistics","statistical","weifenpei","management","jurisdiction","personal"],"role":[],"username":"admin"},"msg":"ok"}

// 退出接口

{
     "code":200,"msg":"ok"}

router/index.js
constantRoutes 拆分开,加了一个asyncRoutes存放动态路由

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

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

/**
 * 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  (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'             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
  },

  {
     
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
     
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: {
      title: '首页', icon: 'dashboard' }
    }]
  },
  {
     
    path: '/Tree',
    component: Layout,
    children: [
      {
     
        path: 'tree',
        name: 'Tree',
        component: () => import('@/views/tree/index'),
        meta: {
      title: '文件树', icon: 'tree' }
      }
    ]
  }
]
/**
 * 动态路由
 */
export const asyncRoutes = [
  {
     
    path: '/friends',
    component: Layout,
    children: [
      {
     
        path: 'management',
        name: 'Form',
        component: () => import('@/views/form/index'),
        meta: {
      title: '动态路由-表格', icon: 'form' }
      }
    ]
  },
  {
     
    path: '/shezhi',
    component: Layout,
    name: 'Nested',
    meta: {
     
      title: '动态路由-设置',
      icon: 'form'
    },
    children: [
      {
     
        path: 'personal',
        component: () => import('@/views/shezhi/index'),
        meta: {
      title: '动态路由-设置', icon: 'example' }
      }
    ]
  },

  // 404 page must be placed at the end !!!
  {
      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


store/modules/user.js
roles状态储存

import {
      login, logout, getInfo } from '@/api/user'
import {
      getToken, setToken, removeToken } from '@/utils/auth'
import {
      resetRouter } from '@/router'

const getDefaultState = () => {
     
  return {
     
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
     
  RESET_STATE: (state) => {
     
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
     
    state.token = token
  },
  SET_NAME: (state, name) => {
     
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
     
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
     
    state.roles = roles
  }
}

const actions = {
     
  // user login
  login({
      commit }, userInfo) {
     
    const {
      mobile, code, password } = userInfo
    return new Promise((resolve, reject) => {
     
      login({
      mobile: mobile.trim(), code: code, password: password }).then(response => {
     
        const {
      data } = response
        console.log(response)
        const token = data.type + ' ' + data.token
        commit('SET_TOKEN', token)
        setToken(token, mobile.trim())
        resolve()
      }).catch(error => {
     
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
      commit, state }) {
     
    return new Promise((resolve, reject) => {
     
      getInfo(state.token).then(response => {
     
        const {
      data } = response
        if (!data) {
     
          reject('Verification failed, please Login again.')
        }
        const {
      username, avatar } = data
        // const roles = data.permissions
        // console.log(response)
        // commit('SET_ROLES', roles)
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
     
        reject(error)
      })
    })
  },

  // user logout
  logout({
      commit, state }) {
     
    return new Promise((resolve, reject) => {
     
      logout(state.token).then(() => {
     
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        commit('SET_ROLES', [])
        resolve()
      }).catch(error => {
     
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
      commit }) {
     
    return new Promise(resolve => {
     
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      commit('SET_ROLES', [])
      resolve()
    })
  }
}

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


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

//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'
// 添加permission
import permission from './modules/permission'
Vue.use(Vuex)

const store = new Vuex.Store({
     
  modules: {
     
    app,
    settings,
    user,
    // 添加permission
    permission
  },
  getters
})

export default store

//src/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'] // 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
      if (hasGetUserInfo) {
     
        // 信息拿到后,用户请求哪就跳转哪
        next()
      } else {
     
        try {
     
          // get user info
          const {
      permissions } = await store.dispatch('user/getInfo')
          const accessRoutes = await store.dispatch('permission/generateRoutes', permissions, {
      root: true })
          console.log(permissions)
          // router.addRoutes(accessRoutes)
          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}`)
          next(`/login`)
          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}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
     
  // finish progress bar
  NProgress.done()
})

在store/modulds目录下添加permission.js
vue-admin-template 动态路由步骤_第1张图片

//store/modules/permission.js
注意部分
如果接口没有返回router>asyncRoutes内path名,注释掉
if (route.children) {
for (const item of route.children) {
if (permissions.includes(item.path)) {
return true
}
}
}
return permissions.includes(route.path),router>asyncRoutes内的路由也会显示

import {
      asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

function hasPermission(permissions, route) {
      
  // permissions = ["/shezhi", "", "jurisdiction", "/friends", "management", "weifenpei", "/call", "/sensSetting", "personal", "dashboard", "yuangong", "callrecords", "callvoice", "allfriends", "behavior", "behavior_shezhi", "mobile_sms", "/statistical", "totaltable", "trendwechat", "wxstatistics", "callstatistics", "statistical", "weifenpei", "management", "jurisdiction", "personal"]
  if (route.meta !== undefined && route.meta.icon !== undefined) {
     
    if (route.children) {
     
      for (const item of route.children) {
     
        if (permissions.includes(item.path)) {
     
          return true
        }
      }
    }
    return permissions.includes(route.path)
  }
  return true
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(asyncRoutes, permissions) {
     
  const res = []
  asyncRoutes.forEach(route => {
     
    const tmp = {
      ...route }
    if (hasPermission(permissions, tmp)) {
     
      if (tmp.children) {
     
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })
  return res
}

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

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

const actions = {
     
  generateRoutes({
      commit }, permissions) {
     
    return new Promise(resolve => {
     
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

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

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"
      >
        
        <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>


vue-admin-template 动态路由步骤_第2张图片
vue-admin-template 动态路由步骤_第3张图片
vue-admin-template 动态路由步骤_第4张图片
vue-admin-template 动态路由步骤_第5张图片

完成了

你可能感兴趣的:(vue.js,javascript)