vue3 framework Vite + vue Router + ts Return to the previous page or home page after login

Item(Vue3): Vite + vue Router + ts

Description of Requirement:

Jump after login:
① Some pages in the project can only be accessed after logging in. If you are not logged in, you will automatically jump to the login page when you visit this page. After completing the login operation, you need to return to this page again

② If you directly access the login page, you will be redirected to the homepage after login

Page access restriction: route guard

When accessing pages, restrict them. Except for some pages that can be accessed without login, other pages that require login can be accessed. When accessing without login, jump to the login page

Add a global pre-guard in the main.ts file: router.beforeEach

1. Find the "index.ts" file under the "router" folder, configure the routing information in the routing file, and set the requiresAuth field value under meta,

If you need to log in to view the page - - - meta: { requiresAuth: true }

Code example:
{
    
    
      path: '/order',
      name: 'order',
      component: () => import('../views/order/index.vue'),
      meta: {
    
    
        title: '我的订单',
        requiresAuth: true,
      }
},

You can view the page without logging in - - - meta: { requiresAuth: false }

Code example:
{
    
    
      path: '/login',
      name: 'login',
      component: () => import('../views/login/index.vue'),
      meta: {
    
    
        title: '登录',
        requiresAuth: false,
      }
},

as the picture shows:
routing configuration

2. Introduce router in the "main.ts" file

import router from './router'

3. Add global guard settings in the "main.ts" file

Code example:
router.beforeEach((to, from, next) => {
    
    
  const token = localStorage.getItem('authToken');
  if(to.meta.requiresAuth) {
    
    
    if(token) {
    
    
      next();
    } else {
    
    
      next({
    
    
        path: '/login',
        query: {
    
     redirect: to.fullPath } // 记住要访问的页面路由地址,后面登录后跳转会用到该值
      })
    }
  } else {
    
    
    next();
  }
})

Note: localStorage.getItem('authToken') is to obtain the token value. If not, it means that you have not logged in. If you log in, you need to save the token value to localStorage when you log in successfully. If you need to set the login expiration time, you need to clear the token value
. , can be placed in a cookie, or other storage methods

At this point, page access restrictions are set. If you need to log in to access the page, enter the page address in the browser and it will automatically jump to the login page.

After login, the page jumps to the previous page or homepage settings:

1. The login page introduces useRoute, useRouter

If the login page is login.vue, import the route in the login.vue file:

import {
    
     useRoute, useRouter } from 'vue-router';

2. Obtain routing information, return to the previous page or jump to the home page after successful login

Obtain the routing parameter "route.query.redirect" field information. If there is a "redirect" field value and it is not empty, it means that you have not logged in and jumped to the login page when visiting other pages. The redirect value records the address of the page. After logging in Then go to the address recorded in "redirect", which is to return to the page you want to visit before.
Otherwise, if there is no "redirect" field information, or the value is empty, you will jump to the homepage after login

Code example:
const router = useRouter();
const route = useRoute();
const redirectUrl = route?.query?.redirect;
const redirectUrlStr = ref('')
if(redirectUrl) {
    
    
  redirectUrlStr.value = redirectUrl.toString();
}
// 请求接口,登录校验
async function loginCheckFn(mobileVal: string, codeVal: string) {
    
    
  const res = await login({
    
     'mobile': mobileVal, 'code': codeVal }); // 按自己实际登录接口请求写
  console.log(res);
  const {
    
     code, reason, result }: any = res;

  if(code == 0) {
    
     // 登录成功
    localStorage.setItem('authToken', result.authToken);
    
    // 返回上一页或者首页
    if(redirectUrl) {
    
    
      router.push({
    
     path: redirectUrlStr.value })
    } else {
    
    
      router.push({
    
     path: '/' });
    }
  } else {
    
     // 登录失败
 	  console.log(reason);
  }

For more routing knowledge, you can view the official documentation of vue Router ~

Guess you like

Origin blog.csdn.net/qq_39111074/article/details/129638508