vue路由守卫

router.beforeEach(async(to, from, next) => {
  /*
  全局前置路由守卫
  to: 要去哪个页面
  from: 从哪里来
  next: 它是一个函数
   如果直接放行next()
   如果要跳转到其它页 next(其它页)

  */
  NProgress.start() // 开始进度条
  const token = store.state.user.token
  // console.log(to)
  if (token) {
    // 去登录页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        // 动态路由添加
        const filterRoutes = asyncRoutes.filter(route => {
          const routeName = route.children[0].name
          return menus.includes(routeName)
        })
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList', filterRoutes)
      }
      next()
    }
  } else {
    // 没有登录 只能去白名单(那些不需要token就可以访问的页面)
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // this.$message.success('你没有登录,转到登录页')
      next('/login')
      NProgress.done()
    }
  }
})
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

你可能感兴趣的:(vue,vue.js,javascript,前端)