Home Web Front-end JS Tutorial How to encapsulate Vue2 route navigation hook and axios interceptor

How to encapsulate Vue2 route navigation hook and axios interceptor

May 25, 2018 pm 02:26 PM
vue2 navigation hook

This time I will show you how to encapsulate the Vue2 routing navigation hook and axios interceptor, and what are the precautions for encapsulating the Vue2 routing navigation hook and axios interceptor. The following is a practical case, let’s take a look together. take a look.

1. Written in front

I have been learning Vue2 recently and encountered some pages that require

user login permissions to request data, and the server response does not meet expectations. Problem, but we can't handle each page separately, so I thought that axios provides a good thing like interceptors, and then this article appeared.

2. Specific requirements

  1. User authentication and redirection: use the routing navigation hook provided by Vue

  2. Request data serialization: use the request interceptor provided by axios

  3. Interface error information processing: use the response interceptor provided by axios

3. Simple implementation

3.1 Encapsulation of authentication and redirection at the routing and navigation hook level

All configurations of routing and navigation hooks are in router/index.js, here It’s part of the code

import Vue from 'vue'
import Router from 'vue-router'
import { getUserData } from '@/script/localUserData'
const MyAddress = r => require.ensure([], () => r(require('@/views/MyAddress/MyAddress')), 'MyAddress')
Vue.use(Router)
const routes = [
 {
  path: '/profile/address',
  name: 'MyAddress',
  component: MyAddress,
  meta: {
   title: '我的地址',
   requireAuth: true
  }
 },
 // 更多...
]
const router = new Router({
 mode: 'history',
 routes
})
Copy after login
Let’s mainly look at the code for the logical processing part below

let indexScrollTop = 0
router.beforeEach((to, from, next) => {
 // 路由进入下一个路由对象前,判断是否需要登陆
 // 在路由meta对象中由个requireAuth字段,只要此字段为true,必须做鉴权处理
 if (to.matched.some(res => res.meta.requireAuth)) {
  // userData为存储在本地的一些用户信息
  let userData = getUserData()
  // 未登录和已经登录的处理
  // getUserData方法处理后如果userData.token没有值就是undefined,下面直接判断
  if (userData.token === undefined) {
   // 执行到此处说明没有登录,君可按需处理之后再执行如下方法去登录页面
   // 我这里没有其他处理,直接去了登录页面
   next({
    path: '/login',
    query: {
     redirect: to.path
    }
   })
  } else {
   // 执行到说明本地存储有用户信息
   // 但是用户信息是否过期还是需要验证一下滴
   let overdueTime = userData.overdueTime
   let nowTime = +new Date
   // 登陆过期和未过期
   if (nowTime > overdueTime) {
    // 登录过期的处理,君可按需处理之后再执行如下方法去登录页面
    // 我这里没有其他处理,直接去了登录页面
    next({
     path: '/login',
     query: {
      redirect: to.path
     }
    })
   } else {
    next()
   }
  }
 } else {
  next()
 }
 if (to.path !== '/') {
  indexScrollTop = document.body.scrollTop
 }
 document.title = to.meta.title || document.title
})
router.afterEach(route => {
 if (route.path !== '/') {
  document.body.scrollTop = 0
 } else {
  Vue.nextTick(() => {
   document.body.scrollTop = indexScrollTop
  })
 }
})
export default router
Copy after login
At this point, the authentication processing at the routing hook level is completed, but if you are careful, you may notice: Navigate to the login page There is a query object in the called next method, which carries the address of the target route. This is because we need to redirect to the target page after successful login.

3.2 Encapsulating the axios interceptor

All configurations of axios are in the script/getData.js file. Here is the public code part of this file

"
import qs from 'qs'
import { getUserData } from '@/script/localUserData '
import router from '@/router '
import axios from 'axios'
import { AJAX_URL } from '@/config/index '
axios.defaults.baseURL = AJAX_URL
> axios请求拦截器代码
 "
/**
 * 请求拦截器,请求发送之前做些事情
 */
axios.interceptors.request.use(
 config => {
  // POST || PUT || DELETE请求时先格式化data数据
  // 这里需要引入第三方模块qs
  if (
   config.method.toLocaleUpperCase() === 'POST' ||
   config.method.toLocaleUpperCase() === 'PUT' ||
   config.method.toLocaleUpperCase() === 'DELETE'
  ) {
   config.data = qs.stringify(config.data)
  }
  // 配置Authorization参数携带用户token
  let userData = getUserData()
  if (userData.token) {
   config.headers.Authorization = userData.token
  }
  return config
 },
 error => {
  // 此处应为弹窗显示具体错误信息,因为是练手项目,劣者省略此处
  // 君可自行写 || 引入第三方UI框架
  console.error(error)
  return Promise.reject(error)
 }
)
Copy after login
axios response interceptor code

/**
 * 响应拦截器,请求返回异常统一处理
 */
axios.interceptors.response.use(
 response => {
  // 这段代码很多场景下没用
  if (response.data && response.data.success === false) {
   // 根据实际情况的一些处理逻辑...
   return Promise.reject(response)
  }
  return response
 },
 error => {
  // 此处报错可能因素比较多
  // 1.需要授权处用户还未登录,因为路由段有验证是否登陆,此处理论上不会出现
  // 2.需要授权处用户登登录过期
  // 3.请求错误 4xx
  // 5.服务器错误 5xx
  // 关于鉴权失败,与后端约定状态码为500
  switch (error.response.status) {
   case 403:
    // 一些处理...
    break
   case 404:
    // 一些处理...
    break
   case 500:
    let userData = getUserData()
    if (userData.token === undefined) {
     // 此处为未登录处理
     // 一些处理之后...再去登录页面...
     // router.push({
     //  path: '/login'
     // })
    } else {
     let overdueTime = userData.overdueTime
     let nowTime = +new Date
     if (overdueTime && nowTime > overdueTime) {
      // 此处登录过期的处理
      // 一些处理之后...再去登录页面...
      // router.push({
      //  path: '/login'
      // })
     } else {
      // 极端情况,登录未过期,但是不知道哪儿错了
      // 按需处理吧...我暴力回到了首页
      router.push({
       path: '/'
      })
     }
    }
    break
   case 501:
    // 一些处理...
    break
   default:
    // 状态码辣么多,按需配置...
    break
  }
  return Promise.reject(error)
 }
)
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

v#detailed explanation of the steps to use the select built-in component of ue

How to operate the vue select component Use and disable

The above is the detailed content of How to encapsulate Vue2 route navigation hook and axios interceptor. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between the life cycle execution order in vue2 and vue3 What is the difference between the life cycle execution order in vue2 and vue3 May 16, 2023 pm 09:40 PM

Difference in life cycle execution order between vue2 and vue3 Life cycle comparison The execution order in vue2 beforeCreate=>created=>beforeMount=>mounted=>beforeUpdate=>updated=>beforeDestroy=>destroyed The execution order in vue3 setup=>onBeforeMount=>onMounted=> onBeforeUpdate=>onUpdated=>onBeforeUnmount=&g

Quickly understand the Vue2 diff algorithm (detailed graphic explanation) Quickly understand the Vue2 diff algorithm (detailed graphic explanation) Mar 17, 2023 pm 08:23 PM

The diff algorithm is an efficient algorithm that compares tree nodes at the same level, avoiding the need to search and traverse the tree layer by layer. So how much do you know about the diff algorithm? The following article will give you an in-depth analysis of the diff algorithm of vue2. I hope it will be helpful to you!

What is the horizontal figure 8 on the navigation map? What is the horizontal figure 8 on the navigation map? Jun 27, 2023 am 11:43 AM

The horizontal figure 8 on the navigation map means haze, moderate is a yellow 8 warning signal, and severe is an orange 8 warning signal.

Baidu Maps App latest version 18.8.0 released, introducing traffic light radar function for the first time and adding real-time parking recommendation function Baidu Maps App latest version 18.8.0 released, introducing traffic light radar function for the first time and adding real-time parking recommendation function Aug 06, 2023 pm 06:05 PM

Both Android and iOS versions of Baidu Map App have released version 18.8.0, which introduces the traffic light radar function for the first time, leading the industry. According to the official introduction, after turning on the traffic light radar, it supports automatic detection of traffic lights while driving without having to enter a destination. Beidou High-Precision can position in real time. , 1 million+ traffic lights across the country automatically trigger green wave reminders. In addition, the new function also provides full silent navigation, making the map area more concise, key information clear at a glance, and no voice broadcast, allowing the driver to focus more on driving. Baidu Maps will launch a traffic light countdown function in October 2020, supporting real-time countdown prediction. Judgment, the navigation will automatically display the remaining seconds of the countdown when approaching a traffic light intersection, allowing users to always grasp the road conditions ahead. Traffic light countdown to December 31, 2022

Which navigation software is the football navigation voice package in? Which navigation software is the football navigation voice package in? Nov 09, 2022 pm 04:33 PM

The football navigation voice package in the "Amap Navigation" software is one of the navigation voice packages for the car version of the Amap map. The content is the navigation voice of Huang Jianxiang's football commentary version. Setting method: 1. Open the Amap software; 2. Click to enter the "More Tools" - "Navigation Voice" option; 3. Find "Huang Jianxiang Passionate Voice" and click "Download"; 4. On the pop-up page, click " Just use voice".

Amap launches upgraded version of driving ETA service: real-time analysis of current road conditions and more accurate estimated arrival time Amap launches upgraded version of driving ETA service: real-time analysis of current road conditions and more accurate estimated arrival time Apr 30, 2024 am 08:37 AM

According to news from this site on April 29, Amap officially announced the launch of an upgraded version of driving ETA (Note from this site: ETA is the estimated time of arrival, which refers to the estimated time it will take for the user to depart from the current moment and follow a given route to the destination. ) service, which aims to help users make more accurate route planning duration and traffic condition estimates, and assist users in making travel decisions. This map application is the latest upgraded Amap App. It introduces the "ultra-large-scale graph convolutional neural network model", which can better capture and learn traffic flow patterns, support urban road networks and highway systems, and can Accurately depict the spatiotemporal dynamic changes of traffic conditions. In addition, the new version of the map further integrates the iTransformer time series prediction model to support real-time analysis.

How to implement image browsing and thumbnail navigation through Vue? How to implement image browsing and thumbnail navigation through Vue? Aug 18, 2023 pm 02:51 PM

How to implement image browsing and thumbnail navigation through Vue? With the development of web applications, pictures play an increasingly important role in our daily lives. In many cases, we need to implement image browsing and thumbnail navigation functions. This article will introduce how to use the Vue framework to implement this function and provide code examples. In Vue, we can use the Vue plug-in to implement image browsing and thumbnail navigation functions. A popular plugin is vue-gallery, which provides a simple and easy-to-use interface

How to implement page jump and navigation in uniapp How to implement page jump and navigation in uniapp Oct 20, 2023 pm 02:07 PM

How to implement page jumps and navigation in uniapp. uniapp is a front-end framework that supports one-time coding and multi-end publishing. It is based on Vue.js. Developers can use uniapp to quickly develop mobile applications. In uniapp, implementing page jumps and navigation is a very common requirement. This article will introduce how to implement page jump and navigation in uniapp, and provide specific code examples. 1. Page jump Use the methods provided by uniapp to jump the page. uniapp provides a set of methods for implementation.

See all articles