Vue routing routing guard

route guard
As the name suggests, the navigation guard provided by vue-router is mainly used to guard the navigation by jumping or canceling. Simply put, it is in the routing jump
Some hooks when jumping from one page to another, you can do something before, during, and after the jump.
What you need to do before and after opening a page.
Each guard method receives parameters:
  • to : the target to be entered, which is a routing object
  • from : The route that the current navigation is about to leave is also a route object
  • next : optional, is a method to go directly to the next route
You can use router.beforeEach to register a global pre-guard, and when a navigation is triggered, this callback function will be executed asynchronously.

to refers to which page to come from, and from means to come from the root directory. to: from where from from: where to go    

//2.创建路由实例并传递上面路由对象routes
    const router = createRouter({
//路由的一种前端展现方式,通常使用这个就行了
        history: createWebHistory(),
        routes
  }
)

//定义前置路由守卫。进入某个页面之前需要干什么
router.beforeEach((to,from,next) => {
    console.log(to)
    console.log(from)
})

router.beforeEach((to, from, next) => {
//如果用户访问登录页,直接放行
    if(to.path == '/login') {
        return next()
}

const token = '' //模拟token,正常是从本地cookie或localstorage中获取

if (token) {
    return next() //如果有token,则正常跳转访问
} else {
    return next('/login') //如果没有token,跳转到登录页
}
})

1. Global guard

1. Global front guard

grammar:

 router.beforeEach((to,from,next)=>{})

Parameter description:
to : which route to enter to
from : which route to leave from
next : function to decide whether to display the route page you want to see.

Example:
Setting global guards in main.js

  • In main.js, there is a route instantiation object router. Setting guards in main.js is already a global guard.
  • As follows, determine whether the path to.path is currently entering is login or registration, and if so, execute next() to display the current interface. If not, an alert pops up and moves to the login screen.
  • In this way, it can be realized that when the user is not logged in, the login interface is always displayed.

router.beforeEach((to,from,next)=>{
  if(to.path == '/login' || to.path == '/register'){
    next();
  }else{
    alert('您还没有登录,请先登录');
    next('/login');
  }})

おすすめ

転載: blog.csdn.net/qq_34556414/article/details/132086651