Home  >  Article  >  Web Front-end  >  Implementation method of vue login route verification

Implementation method of vue login route verification

小云云
小云云Original
2018-05-15 14:45:143002browse

If the login status of a vue project is managed using vuex status, the status managed by vuex will disappear as soon as the page is refreshed, so login route verification will be meaningless. The login status can be written to web Storage for storage management. This article mainly introduces the implementation of Vue login route verification in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

The steps are as follows:

1. In the login component, write the login status into web Storage. (Generally written to session Storage, the session is closed and the stored data is automatically deleted)

if('登录成功') 
 {sessionStorage.setItem('accessToken' , 写入登录成功返回的登录令牌或者自定义的判断字符串) }

2. Add the login verification identifier requiresAuth (customized) to the routing meta information that requires login verification
[html] view plain copy

routers: [ 
      { path: '/listInfo', 
         name: 'listInfo', 
         component: listInfo, 
         meta: { requiresAuth: true  
               } 
          } 
       ]

3. Verify whether the page requires login in the global hook function beforeEach

router.beforeEach((to, from, next) => {  
    //to即将进入的目标路由对象,from当前导航正要离开的路由, next : 下一步执行的函数钩子
    if(to.path === '/login') { next() } // 如果即将进入登录路由,则直接放行
     else {   //进入的不是登录路由
         if(to.meta.requiresAuth && !sessionStorage.getItem('accessToken')) {next({ path: '/login' })} 
       //下一跳路由需要登录验证,并且还未登录,则路由定向到 登录路由
       else { next() }} 
      //如果不需要登录验证,或者已经登录成功,则直接放行
    }

Note: the global hook beforeEach should be placed in front of the global component and behind the global component. The Vue instance has been loaded. At this time, directly enter the route you want to go to in the address bar of the browser, and you will not be directed to the login route.

Related recommendations:

Detailed explanation of routing verification and corresponding interception usage in vue

PHP Framework Simple Router

How to solve the routing error when building routing in Vue.js?

The above is the detailed content of Implementation method of vue login route verification. 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