动态路由大体实现

This commit is contained in:
pixelqm
2019-09-14 22:30:04 +08:00
parent 6738d0eb1a
commit a0fab80d28
10 changed files with 298 additions and 72 deletions
+36
View File
@@ -0,0 +1,36 @@
import { asyncRouterHandle } from '@/utils/asyncRouter';
import { asyncMenu } from '@/api/menu'
export const router = {
namespaced: true,
state: {
asyncRouters: []
},
mutations: {
// 设置动态路由
setAsyncRouter(state, asyncRouters) {
state.asyncRouters = asyncRouters
}
},
actions: {
// 从后台获取动态路由
async SetAsyncRouter({ commit }) {
const asyncRouterRes = await asyncMenu()
const asyncRouter = asyncRouterRes.data.menus
asyncRouter.push({
path: '*',
redirect: '/404'
})
asyncRouterHandle(asyncRouter) // 等待动态使用 VUEX持久化 会将其放入 vuex并且动态生成左侧列表
commit('setAsyncRouter', asyncRouter)
}
},
getters: {
// 获取动态路由
asyncRouters(state) {
return state.asyncRouters
}
}
}
+30 -8
View File
@@ -1,5 +1,6 @@
import { login } from '@/api/user'
import router from '@/router/index'
import { Message } from 'element-ui'
export const user = {
namespaced: true,
state: {
@@ -9,7 +10,8 @@ export const user = {
headerImg: "",
authority: "",
},
token: ""
token: "",
expiresAt: ""
},
mutations: {
setUserInfo(state, userInfo) {
@@ -19,23 +21,43 @@ export const user = {
setToken(state, token) {
// 这里的 `state` 对象是模块的局部状态
state.token = token
},
setExpiresAt(state, expiresAt) {
// 这里的 `state` 对象是模块的局部状态
state.expiresAt = expiresAt
}
},
actions: {
LoginIn({ commit }, loginInfo) {
login(loginInfo).then(res => {
async LoginIn({ commit }, loginInfo) {
try {
const res = await login(loginInfo)
commit('setUserInfo', res.data.user)
commit('setToken', res.data.token)
return res
}).catch(err => {
console.error(err)
commit('setExpiresAt', res.data.expiresAt)
if (res.success) {
const redirect = router.history.current.query.redirect
if (redirect) {
router.push({ path: redirect })
} else {
router.push({ path: '/layout/dashboard' })
}
}
} catch (err) {
Message({
type: 'error',
message: err,
showClose: true
})
return Promise.reject(err)
})
}
}
},
getters: {
userInfo(state) {
return state.userInfo
},
token(state) {
return state.token
}
}
}