vue-admin-template实现角色权限管理方式一

背景:前面提到测试工具箱整合页面集成后台,使用了vue作为前端,python的django作为后端,vue前端框架选择了 vue-admin-template(这是一个基础版本) 基础版本
既然是后台就会涉及到权限控制,基础版本的vue-admin-template 是没有路由权限控制的,最后是看 vue-element-admin 的 手摸手,带你用vue撸后台 系列二(登录权限篇) 对照的改的

vue-admin-template简介:
下载地址:vue-admin-template
vue-admin-template实现角色权限管理方式一_第1张图片

1、修改 router/index.js

#所有权限通用路由表 
#如首页和登录页和一些不用权限的公用页面
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: 'Dashboard', icon: 'dashboard' }
    }]
  },
  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]

新增 asyncRoutes 动态路由

#异步挂载的路由
#动态需要根据权限加载的路由表 
export const asyncRoutes = [
  {
    path: '/tool',
    component: Layout,
    redirect: '/tool/table',
    name: 'tool',
    alwaysShow: true,
    meta: {
      title: '工具箱',
      icon: 'el-icon-s-help',
      roles: ['admin']
    },
    children: [
      {
        path: 'mobilecode',
        component: () => import('@/views/tool/mobilecode'),
        name: 'mobilecode',
        meta: { title: '手机号生成验证码', roles: ['admin'] }
      }, 
    ]
  },
  { path: '*', redirect: '/404', hidden: true }
]

根据 vue-router官方推荐 的方法通过meta标签来标示改页面能访问的权限有哪些。如meta: { role: [‘admin’,‘super_editor’] }表示该页面只有admin和超级编辑才能有资格进入

2、新增store/modules/permission.js文件

这个文件直接从集成版本里复制一份过来就行

3、修改store/modules/user.js

roles必须是array数组 后台返回的是roles:[‘admin’]这样格式的

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_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

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().then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败,请重新登录')
        }
        const { name, roles, avatar } = data
        if (!roles || roles.length <= 0) {
          reject('getInfo:roles must be a non-null array!')
        }

        commit('SET_NAME', name)
        commit('SET_ROLES', roles)
        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')
      resolve()
    })
  }
}

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


4、修改 store/ getter.js 和 index.js

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  refreshToken: state => state.user.refreshToken,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  roles: state => state.user.roles,
  permission_routers: state => state.permission.routes
}
export default getters

这里参考的是 vue-element-admin 中的方法

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
const store = new Vuex.Store({
  modules,
  getters
})
export default store

5、修改src/permission.js

照着admin中的permission.js 复制过来就行

6、修改layout/components/Sidebar/index.vue

 <sidebar-item v-for="route in permission_routers" :key="route.path" :item="route" :base-path="route.path" />

新增permission_routers
computed: {
    ...mapGetters([
      'permission_routers',
      'sidebar'
    ]),

你可能感兴趣的:(vue,Python,Django,vue.js,前端,前端框架)