【vue】 router.beforeEach

import store from '@/store'
const Vue = require('vue')
const Router = require('vue-router')
Vue.use(Router)

const router = new Router({
  scrollBehavior (to, from, savedPosition) {
    return {x: 0, y: 0}
  },
  linkActiveClass: 'is-active',
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'index',
      component: resolve => require([`@/views/index.vue`], resolve)
    },
    {
      path: '/process',
      name: 'process',
      meta: {
        role: 1,
        crumbName: ['管理中心'],
        crumbPath: []
      },
      component: resolve => require([`@/views/process.vue`], resolve)
    },
    {
      path: '*',
      redirect: '/'
    }
  ]
})
router.beforeEach(async (to, from, next) => {
  let loginUserName = store.getters.loginUserName
  let loginUserRole = store.getters.loginUserRole
  let goNext = (to, from, next, loginUserRole) => {
    if (to.meta.role !== undefined && loginUserRole < to.meta.role) {
      ...(想要做的操作)
      next()
    } else {
      next()
    }
  }
  try {
    if (!loginUserName) { // 先判断是否已登录
      await store.dispatch('getUserInfo')
      // await store.dispatch('getUserRole')
      let loginUserName = store.getters.loginUserName
      let loginUserRole = store.getters.loginUserRole
      if (loginUserName) {
        goNext(to, from, next, loginUserRole)
      }
    } else {
      goNext(to, from, next, loginUserRole)
    }
  } catch (err) {}
})

export default router
 

  

posted @ 2019-10-17 20:19  xiiiiiimi  阅读(809)  评论(0编辑  收藏  举报