Home >Web Front-end >JS Tutorial >How vue implements the code for monitoring routing

How vue implements the code for monitoring routing

不言
不言Original
2018-09-08 16:16:292290browse

This article brings you the code about how Vue implements monitoring routing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the vue project, a feasible routing rule is very important. It determines whether the user has permission to enter the route, and some routes must jump when refreshing, etc.
This part of the code is used It is completed by the router, one of the vue family buckets. Let’s see the specific example below

const whiteList = ['/login']  // 路由白名单,不需要登录的路由放在这里面
router.beforeEach((to,from,next) => {  // 监听路由刷新进行跳转  
window.addEventListener('load',function () {
    console.log(from.path)    
    console.log(to.path)    
    if (to.path == '/groupwork') {
      next({ path: '/choice_course' })
    }
  })  if (store.state.token) {    
  if (to.path === '/login') { // 如果当前用户输入的是登录路由,那么就定向到 /choice_course 路由
      next('/choice_course')
    } else {      
    if (!store.state.nickname) { // 判断用户信息是否存在,不存在就拉取用户信息
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          next()
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {  // 发生错误就直接清除token,重新登录
            next({ path: '/login' })
          })
        })
      } else {
        next()
      }
    }
  } else {    
  if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})

Related recommendations:

How to use the Vue data monitoring method watch

vue computed properties and listener case code analysis

The above is the detailed content of How vue implements the code for monitoring routing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more