Skip to content

Commit

Permalink
'动态路由'
Browse files Browse the repository at this point in the history
  • Loading branch information
lujiehui committed Nov 27, 2019
1 parent 89dd3d9 commit 9143b69
Show file tree
Hide file tree
Showing 21 changed files with 176 additions and 105 deletions.
4 changes: 2 additions & 2 deletions mock/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ const tokens = {

const users = {
'admin-token': {
roles: 'admin',
role: 'admin',
introduction: 'I am a super administrator',
avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
name: 'Super Admin'
},
'editor-token': {
roles: 'editor',
role: 'editor',
introduction: 'I am an editor',
avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
name: 'Normal Editor'
Expand Down
16 changes: 0 additions & 16 deletions src/components/SrmForm/SrmValueRegio.vue
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,9 @@ export default {
},
rules: {
min: [
// { required: true, message: '请输入必填项', trigger: 'blur' },
// { validator: this.validateCom, trigger: 'blur' },
{ validator: this.validateMin, trigger: 'blur' }
],
max: [
// { required: true, message: '请输入必填项', trigger: 'blur' },
// { validator: this.validateCom, trigger: 'blur' },
{ validator: this.validateMax, trigger: 'blur' }
]
}
Expand Down Expand Up @@ -90,18 +86,6 @@ export default {
})
return validRes
},
// validateCom(rule, value, callback) {
// const one = Number(value)
// if (Number.isInteger(one)) {
// if (one < MIN_NUMBER) {
// return callback(new Error('输入值必须大于0'))
// } else if (one > MAX_NUMBER) {
// return callback(new Error('输入值必须小于100000'))
// }
// return callback()
// }
// return callback(new Error('输入值必须为正整数'))
// },
validateMin(rule, value, callback) {
const one = Number(value)
const max = Number(this.valueForm.max)
Expand Down
19 changes: 11 additions & 8 deletions src/components/SrmForm/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
:is="inline ? 'span' : 'el-col'"
:key="index + item.attrs.key || item.slot"
:span="item.itemAttrs.col || 24"
:style="{'min-width': item.itemAttrs.width +'px', 'max-width': item.itemAttrs.width + 'px'}"
>
<el-form-item
v-if="item._ifRender"
Expand Down Expand Up @@ -144,11 +143,17 @@ export default {
handler() {
this.formItems.forEach(formItem => {
if (!formItem.attrs || !formItem.attrs.key) return // 跳过没有key的属性(插槽)
this.$set(
this.Model,
formItem.attrs.key,
formItem.attrs.value ? formItem.attrs.value : ''
)
let value = formItem.attrs.value
if (formItem.tag === 'value-regio') {
value = value || {}
}
if (value) {
this.$set(
this.Model,
formItem.attrs.key,
value
)
}
})
this.originModel = JSON.parse(JSON.stringify(this.Model))
},
Expand Down Expand Up @@ -209,8 +214,6 @@ export default {
this.$refs[form].validate(async valid => {
if (valid) {
try {
// const res = await this.api(this.Model)
// this.$emit('after-submit', res)
this.$emit('submit')
} catch (e) {
console.log(e)
Expand Down
2 changes: 2 additions & 0 deletions src/icons/svg/article.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 4 additions & 4 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ import SrmDialogCheck from '@/components/SrmDialogCheck'
* Currently MockJs will be used in the production environment,
* please remove it before going online! ! !
*/
// import { mockXHR } from '../mock'
// if (process.env.NODE_ENV === 'production') {
// mockXHR()
// }
import { mockXHR } from '../mock'
if (process.env.NODE_ENV === 'production') {
mockXHR()
}

// set ElementUI lang to EN
Vue.use(ElementUI, {
Expand Down
9 changes: 3 additions & 6 deletions src/permission.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,16 @@ router.beforeEach(async(to, from, next) => {
NProgress.done()
} else {
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
const hasRoles = store.getters.role
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')
const { role } = await store.dispatch('user/getInfo')

// generate accessible routes map based on roles
const accessRoutes = await store.dispatch('router/generateRoutes', roles)

console.log(roles, accessRoutes, '!!!')
const accessRoutes = await store.dispatch('router/generateRoutes', role)

// dynamically add accessible routes
router.addRoutes(accessRoutes)
Expand Down
9 changes: 1 addition & 8 deletions src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,19 @@ export const constantRoutes = [
path: 'dashboard',
component: () => import('@/views/dashboard/index'),
name: 'Dashboard',
meta: { title: 'Dashboard', icon: 'dashboard', affix: true }
meta: { title: '首页', icon: 'dashboard', affix: true }
}
]
}
]

/**
* asyncRoutes
* the routes that need to be dynamically loaded based on user roles
*/

const files = require.context('./modules', false, /\.js$/)
const modules = []

files.keys().forEach(key => {
modules.push(files(key).default)
})

console.log(modules, 'modules')
export const asyncRoutes = [
...modules,
// 404 page must be placed at the end !!!
Expand All @@ -89,7 +83,6 @@ const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
router.$route.push('/login')
}

export default router
30 changes: 30 additions & 0 deletions src/router/modules/article.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/** When your routing table is too long, you can split it into small modules **/

import Layout from '@/layout'

const ArticleRouter = {
path: '/article',
component: Layout,
redirect: '/article/list',
name: 'Article',
meta: {
title: '文章管理',
icon: 'article'
},
children: [
{
path: 'list',
component: () => import('@/views/article'),
name: 'ArticleList',
meta: { title: '文章管理' }
},
{
path: 'detail',
component: () => import('@/views/article/detail'),
name: 'ArticleDetail',
meta: { title: '文章详情', noCache: true },
hidden: true
}
]
}
export default ArticleRouter
18 changes: 12 additions & 6 deletions src/router/modules/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ import Layout from '@/layout'
const formRouter = {
path: '/form',
component: Layout,
redirect: '/form/adform',
redirect: '/form/example1',
name: 'Form',
meta: {
title: 'Form',
title: '高级表单',
icon: 'form'
},
children: [
{
path: 'adform',
component: () => import('@/views/form/myForm'),
name: 'MyForm',
meta: { title: 'ad form' }
path: 'example1',
component: () => import('@/views/form/example1'),
name: 'FormExample1',
meta: { title: '案例一' }
},
{
path: 'example2',
component: () => import('@/views/form/example2'),
name: 'FormExample2',
meta: { title: '案例二' }
}
]
}
Expand Down
23 changes: 16 additions & 7 deletions src/router/modules/table.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,27 @@ import Layout from '@/layout'
const tableRouter = {
path: '/table',
component: Layout,
redirect: '/table/complex-table',
redirect: '/table/example1',
name: 'Table',
meta: {
title: 'Table',
icon: 'table'
title: '高级表格',
icon: 'table',
roles: ['admin']
},
children: [
{
path: 'my',
component: () => import('@/views/table/my'),
name: 'DynamicTable',
meta: { title: 'Dynamic Table' }
path: 'example1',
component: () => import('@/views/table/example1'),
name: 'TableExample1',
meta: { title: '案例一' },
roles: ['admin']
},
{
path: 'example2',
component: () => import('@/views/table/example2'),
name: 'TableExample2',
meta: { title: '案例二' },
roles: ['admin']
}
]
}
Expand Down
2 changes: 1 addition & 1 deletion src/store/getters.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ const getters = {
name: state => state.user.name,
routes: state => state.router.routes,
addRoutes: state => state.router.addRoutes,
roles: state => state.user.roles
role: state => state.user.role
}
export default getters
50 changes: 44 additions & 6 deletions src/store/modules/router.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,63 @@
import { constantRoutes, asyncRoutes } from '@/router'

/**
* Use meta.role to determine if the current user has permission
* @param roles
* @param route
*/
function hasPermission(role, route) {
if (route.meta && route.meta.roles) {
return 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) => {
SET_ROUTE: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes
.concat(routes) // 添加用户角色对应的路由
},
RESET_ROUTE: (state) => {
state.addRoutes = []
state.routes = constantRoutes
}
}

const actions = {
generateRoutes({ commit }, roles) {
console.log(roles, 'payload')
// TODO:: 根据角色获取具体的路由
generateRoutes({ commit }, role) {
// 根据角色获取具体的路由
const accessedRoutes = filterAsyncRoutes(asyncRoutes, role)
return new Promise(resolve => {
commit('SET_ROUTES', asyncRoutes)
resolve(asyncRoutes)
commit('SET_ROUTE', accessedRoutes)
resolve(accessedRoutes)
})
}
}
Expand Down
Loading

0 comments on commit 9143b69

Please sign in to comment.