vue 路由动态权限
1.菜单路由全由后端接口返回
1.1 第一步:拿到后端返回数据
login() {
this.$http.post('api/permission/getMenu', this.form).then(res => {
res = res.data
if (res.code === 20000) {
调用vuex方法
this.$store.commit('setMenu', res.data.menu)
this.$store.commit('addMenu', this.$router)
} else {
this.$message.warning(res.data.message)
}
})
}
返回数据格式:
menu: [
{
path: '/',
name: 'home',
label: '首页',
icon: 's-home',
url: 'Home/Home'
},
{
path: '/video',
name: 'video',
label: '视频管理页',
icon: 'video-play',
url: 'VideoManage/VideoManage'
},
{
path: '/user',
name: 'user',
label: '用户管理页',
icon: 'user',
url: 'UserManage/UserManage'
},
{
label: '其他',
icon: 'location',
children: [
{
path: '/page1',
name: 'page1',
label: '页面1',
icon: 'setting',
url: 'Other/PageOne'
},
{
path: '/page2',
name: 'page2',
label: '页面2',
icon: 'setting',
url: 'Other/PageTwo'
}
]
}
],
1.2:使用vuex传递数据并储存
import Cookie from 'js-cookie'
export default {
state: {
currentMenu: null,
menu: []
},
mutations: {
setMenu(state, val) {
state.menu = val
Cookie.set('menu', JSON.stringify(val))
},
addMenu(state, router) {
if (!Cookie.get('menu')) {
return
}
let menu = JSON.parse(Cookie.get('menu'))
state.menu = menu
let currentMenu = [
{
path: '/',
component: () => import(`@/views/Main`),
children: []
}
]
menu.forEach(item => {
if (item.children) {
item.children = item.children.map(item => {
item.component = () => import(`@/views/${item.url}`)
return item
})
currentMenu[0].children.push(...item.children)
} else {
item.component = () => import(`@/views/${item.url}`)
currentMenu[0].children.push(item)
}
})
router.addRoutes(currentMenu)
},
1.3:缩减router.js,值留一个登录
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/login',
name: 'login',
component: () => import('@/views/Login/Login')
}
]
})
1.4:main.js里防止刷新丢失
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 全局配置
import '@/assets/scss/reset.scss'
import 'element-ui/lib/theme-chalk/index.css'
import http from '@/api/config'
import './mock'
// 第三方包
import ElementUI from 'element-ui'
Vue.use(ElementUI)
Vue.prototype.$http = http
Vue.config.productionTip = false
router.beforeEach((to, from, next) => {
// 防止刷新后vuex里丢失token
store.commit('getToken')
// 防止刷新后vuex里丢失标签列表tagList
store.commit('getMenu')
let token = store.state.user.token
// 过滤登录页,防止死循环
if (!token && to.name !== 'login') {
next({ name: 'login' })
} else {
next()
}
})
new Vue({
router,
store,
render: h => h(App),
created() {
//防止刷新丢失
store.commit('addMenu', router)
}
}).$mount('#app')