欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue-admin-template 动态路由的实现示例

程序员文章站 2022-03-02 08:55:35
提供登录与获取用户信息数据接口在api/user.js中import request from '@/utils/request'const api = { takeout: '/student/s...

提供登录与获取用户信息数据接口

在api/user.js中

import request from '@/utils/request'
const api = {
  takeout: '/student/students/takeout/',
  loginin: '/student/students/loginin/',
  studentinfo:'/student/students/studentinfo/',
}
export function login(parameter) {
  return request({
    url: api.loginin,
    method: 'get',
    params: parameter
  })
}

export function getinfo(token) {
  return request({
    url: api.studentinfo,
    method: 'get',
    params: {'token':token}
  })
}

export function logout() {
  return request({
    url: api.takeout,
    method: 'get'
  })
}

登录接口数据

{'code': 200, 'data': {'token': 'x-admin'}, 'message': "操作成功"}

退出接口数据

{'code': 200, 'data': 'success', 'message': "操作成功"}

详情接口数据

{
    "code": 200,
    "data": {
        "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        "name": "黄晓果",
        "roles": [
            "editor"
        ]
    }
}

改造router/index.js

import vue from 'vue'
import router from 'vue-router'

vue.use(router)

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

// 基础路由
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: 'el-icon-menu' }
    }]
  },
]

/**
 * 动态路由
 */
export const asyncroutes = [
  {
    path: '/studentinformation',
    component: layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/studentinformation/index'),
        meta: { title: '学生信息', icon: 'el-icon-s-check' }
      }
    ]
  },
  {
    path: '/lecturerinformation',
    component: layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/lecturerinformation/index'),
        meta: { title: '讲师信息', icon: 'el-icon-s-custom', roles: ['editor'] }
      }
    ]
  },
  {
    path: '/coursemanage',
    component: layout,
    meta: { roles: ['admin'] },
    children: [
      {
        path: 'index',
        component: () => import('@/views/coursemanage/index'),
        meta: { title: '课程管理', icon: 'el-icon-s-platform'}
      }
    ]
  },
  // 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

将动态显示的路由写在asyncroutes 中并添加 roles ,例如meta: { roles: [‘admin'] },

在store/modulds目录下添加permission.js

vue-admin-template 动态路由的实现示例

import { asyncroutes, constantroutes } from '@/router'

/**
 * 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)
  }
}

const actions = {
  generateroutes({ commit }, roles) {
    return new promise(resolve => {
      const accessedroutes = filterasyncroutes(asyncroutes, roles)
      commit('set_routes', accessedroutes)
      resolve(accessedroutes)
    })
  }
}

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

修改store/modulds/user.js

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 { username, password } = userinfo
    return new promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('set_token', data.token)
        settoken(data.token)
        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) {
          return reject('验证失败,请重新登录')
        }

        const {roles, name, avatar } = data
        commit('set_roles', roles)
        commit('set_name', name)
        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
}

添加roles: [] 保存权限列表 ,添加内容如下

const getdefaultstate = () => {
  return {
    ...
    roles: []
  }
}

const mutations = {
  ...
  set_roles: (state, roles) => {
    state.roles = roles
  }
}

  // get user info
  getinfo({ commit, state }) {
    return new promise((resolve, reject) => {
      getinfo(state.token).then(response => {
        ...
        const {roles, name, avatar } = data
        commit('set_roles', roles)
        ...
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new promise((resolve, reject) => {
      logout(state.token).then(() => {
        ...
        commit('set_roles', [])
        ...
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resettoken({ commit }) {
    return new promise(resolve => {
      ...
      commit('set_roles', [])
      ...
    })
  }
}

在store/getters.js中添加roles

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

将permission添加到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

最后修改根目录下的permission.js

import router, { constantroutes } 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 hasroles = store.getters.roles && store.getters.roles.length > 0
      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')
          console.log(roles)
          // generate accessible routes map based on roles
          const accessroutes = await store.dispatch('permission/generateroutes', roles)
          // dynamically add accessible routes
          router.options.routes = constantroutes.concat(accessroutes)
          router.addroutes(accessroutes)
          
          // hack method to ensure that addroutes is complete
          // set the replace: true, so the navigation will not leave a history record
          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()
})

将数据绑定到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>

到此这篇关于vue-admin-template 动态路由的实现的文章就介绍到这了,更多相关vue-admin-template 动态路由的实现内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!