1.定义路由时,分
应用路由,需权限控制
使用前要验证权限 : router.beforeEach
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch(‘mutations方法名‘,值)
commit:同步操作,写法:this.$store.commit(‘mutations方法名‘,值)
router.beforeEach(async (to, from, next) => { if (to.path === ‘/error‘) { next() //进入下一个钩子函数 } else { if (getToken() && getToken() !== null) { // 已经登录存在有token // 如果已经生成过路由,不需要再次生成动态路由 if (addRouteFlag) { next() //进入下一个钩子函数 } else { // 同步获取用户信息,动态添加权限路由 await store.dispatch(‘syncCurrentUser‘) let accessRoutes = await store.dispatch(‘generateRoutes‘) let newRouteTmp = [] newRouteTmp.push(accessRoutes) router.addRoutes(newRouteTmp) addRouteFlag = accessRoutes next({ ...to, replace: true }) } } else { // 还没有登录 jquery.getScript(‘http://172.16.13.64:9995/cloudiip-cas/open-login-api.jsp?_=1556259574232‘, async () => { let loginCode = auth.code if (loginCode === 1001) { // 其他地方没有登录 let location = window.location.href let locTemp = encodeURIComponent(location) window.location.href = ‘http://172.16.13.64:9995/cloudiip-cas/login?service=‘ + locTemp next() } else if (loginCode === 1) { // 其他地方已经登录 if (auth.message) { setToken(auth.message) if (addRouteFlag) { next() } else { // 同步获取用户信息,动态添加权限路由 let authorities = await store.dispatch(‘syncCurrentUser‘) let accessRoutes = await store.dispatch(‘generateRoutes‘, authorities, { root: true }) let newRouteTmp = [] newRouteTmp.push(accessRoutes) router.addRoutes(newRouteTmp) addRouteFlag = accessRoutes next({ ...to, replace: true }) } } else { next({ path: ‘/error‘ }) } } else { // 其他情况 next({ path: ‘/error‘ }) } }) } } })
常用无权限控制路由
常用路由就直接使用
const router = new Router({
scrollBehavior: () => ({ y: 0 }),//跳转到一个新的页面的时候,显示最顶端
routes: constantRoutes
})
原文:https://www.cnblogs.com/joer717/p/10830944.html