Use vue vue-router beforEach achieve routing screening to determine a user logs Jump

This article is reproduced in: Ape 2048 Website ➞ https://www.mk2048.com/blog/blog.php?id=i011hjakaa

Respect for the individual original, please indicate the source.

demand

In the development webApp time, taking into account the user experience, often you will not need to call the Page Setup personal data as tourists can visit, and when the user needs to enter some personal data, such as shopping carts, personal center, my wallet, etc. verification judge during login, if the judge has logged in, the page is displayed, if the judgment is not logged in, you jump directly to the login page prompts the user to log in, under today to share how to use beforEach method vue-router to achieve this demand .

achieve

This article assumes you already use webpackor vue-clito set up the environment, and has some vue basis, if you're a novice, then search on the Internet is like, very much related articles, not repeat them here. Man of few words said, directly on the code. In order to facilitate future maintainability of the code, I put in a relevant way to write a new file filter.js

Next, enter the file filter.js, first introduced vue-router: import router from "./router";Then we use the router.beforEachmethod:

router.beforeEach((to, from, next) => {
    //根据字段判断是否路由过滤
    if (to.matched.some(record => record.meta.auth)) {
        if (getToken() !== null) {
            next()
        } else {
            //防止无限循环
            if (to.name === 'login') {
                next();
                return
            }
            next({
                path: '/login',
            });
        }
    } else {
        next()//若点击的是不需要验证的页面,则进行正常的路由跳转
    }
});

beforEach fact vur-router hook function, can be understood as a way to jump before each router will be called, since there before Similarly Of course, there afterEach, that we revisit later.

First, let's explain beforEach three parameters:

  1. to: routing object is about to enter the router.
  2. from: the current navigation route was about to leave.
  3. next: a function, be sure to call this method to resolve this hook. Implementation of the results depend on the method call parameters next.
  • next(): The next hook pipeline. If all the hook either finished, the status of navigation is confirmed (acknowledged).
  • next(false): Interrupt the current navigation. If the browser's URL has changed (manually by the user or may be the browser back button), then it will be reset to a URL address from an address corresponding to the route.
  • next ( '/') or next ({path: '/' }): jump to a different address. The current navigation is interrupted, then a new navigation. You can pass next to the object at any position, and provided such as to allow replace: true, name: 'homeoption or the like and used to prop or any router.push router-link in the options noted that, by next query pass parameters.
  • next(error): (2.4.0+) if its argument is a next Error instance, the navigation will be terminated and the error will be passed to router.onError () registered callbacks.

Explanation

Well, see here may be some people still do not understand, it does not matter, then I can give an example to understand.
Suppose we currently have three routes: /home,/mine,/login
Our initial entry to /home, and this time click on the jump /mine, but because we have not signed, it will automatically jump to /login
in the above case,
to: represent the route /mine, we have to enter the route.
from: represents the route /home, the route we are going to leave.
Note that using beforEach finally had to call next(), otherwise it will error if you do not pass parameters, we will succeed to enter /mine, if we pass parameters, for example next('/login'), then we click on any routes will jump to the /logininterface.
But our needs are only a click is required to verify the login page before jumping to intercept, therefore, we need to add some conditions to be screened to determine the route.

 if (to.matched.some(record => record.meta.auth)) {
        if (getToken() !== null) {
            next()
        }
    }

Here is to talk to the above parameters, to.matchedis an array of objects, which have relevant information to point to the route, such as: path, name, meta, and so on.
We call the array with some () method returns the value trueor falsedetermination is performed, so we need for our judgment jump routes authenticated login to add a field router.js routing configuration file is determined as a condition

    {
      path: '/mine',
      name: 'mine',
      component: mine,
      meta:{auth:true}  //我们自己添加的字段
    }

Due to the routing adds meta:{auth:true}, so we to.matched.some(record => record.meta.auth)will return true, then we can do login judge, my project is credited by the token to localstoragebe judged, getToken () is a package I get localstoragemethod.

 if (getToken() !== null) {
            next()//若token不为null,则进行路由跳转
        }

If there is no token, we proceed to determine the next step, which is the ultimate goal, interception route, jump to the login page

    else {
            next({
                path: '/login',
            });
        }

But this time we encounter a new problem, open the console will find an infinite loop route and will eventually collapse, which is what causes it? Carefully read the bold red above, we can understand

  • next() A route is successful, direct access to the route, will not be called again router.beforeEach ()
  • next({ path: '/login', }); A route is a successful intercept, redirect to login, calls router.beforeEach again ()

That beforeEach () must be called next (), otherwise there will be an infinite loop
next () and next ( 'xxx') is not the same, the difference is that the former does not call router.beforeEach again (), the latter will be. And because we do not token, so after recalling router.beforeEach (), will enter again

 else {
            next({
                path: '/login',
            });
        }

It caused an infinite loop, to solve this problem is also very simple, we are next({ path: '/login', });before a judge conditions increase

 if (to.name === 'login') {
                next();
                return
        }

If we are directed to route name == 'login', execute next();and return the termination code to run.

These are routed intercepted by router.beforEach method, we can not only log in judgment, you can achieve a lot of demand by this method, as long as the routing can jump, but to stimulate the next, if there are places where wrong or there are better ways directly in the comments to tell me, thank you very much.

tips

2018.7.2
As the actual project many interfaces need to be validated token is intercepted, and therefore decided to consider after filtration provided axios interceptor http response 拦截器, the rear end of the error code is returned to determine the token is invalid or expired like wrong to jump to the login page.

Guess you like

Origin www.cnblogs.com/qianduanwriter/p/11788050.html