Home  >  Article  >  Web Front-end  >  How to implement page jump in vue (jump without login)

How to implement page jump in vue (jump without login)

不言
不言Original
2018-07-17 16:58:346919browse

This article brings you content about how vue implements page jumps (non-login jumps). The content is very detailed. Friends in need can refer to it.

Environment: vue 2.9.3 ; webpack;vue-router

Purpose: To achieve non-login jump

Example: Enter directly in the url address bar.../home, but this page requires logging in before entering , the judged value is judged by the token stored in the local cache after logging in. If there is no token, it will jump to the login page. If there is one, it will be opened.

Illustration:

1. Directly enter http://127.0.0.1:9000/#/home in the url address bar, but the page will jump directly to the login page, and there will be parameters.

##vue-router needs to be installed

First configure routing

/src/router/index.js

import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',// 登录
      name: 'Login',
      component: resolve => require(['@/PACS/pages/Login'],resolve)
    },{
      path: '/home',
      name: 'Home',
      meta: {
        requireAuth: true,  // 判断是否需要登录      },
      component: resolve => require(['@/PACS/pages/Home'],resolve)
    } 
    ]

})

## Added field requireAuth to determine whether the route requires login.

Then configure main.js

//  路由判断登录 根据路由配置文件的参数router.beforeEach((to, from, next) => {  if (to.matched.some(record => record.meta.requireAuth)){  // 判断该路由是否需要登录权限
    console.log('需要登录');    if (localStorage.token) {  // 判断当前的token是否存在 ; 登录存入的token      next();
    }    else {
      next({
        path: '/',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由      })
    }
  }  else {
    next();
  }
});

Here is the token saved when logging in

##In this case, you will jump directly to the login page when you log in.

To achieve successful login and then jump back to the page where you started typing, you need to use the value passed later.

If redirect is included, jump to the page just entered.

Note: It is unreasonable to save user data to localstorage. Here is just an idea. If the browser data is not cleared after logging in, the token will always exist and the judgment will be invalid.

Related recommendations:

Vue-router routing judgment page is not logged in and jumps to the login page

The above is the detailed content of How to implement page jump in vue (jump without login). 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