search
HomeWeb Front-endJS TutorialEncapsulate Vue2 routing navigation hook and use it in actual combat

This time I will bring you encapsulation of Vue2 routing and navigation hooks and use them in actual combat. What are the precautions for encapsulating Vue2 routing and navigation hooks and using them in actual combat? The following is a practical case, let's take a look.

1. Written in front

I have been learning Vue2 recently and encountered the problem that some pages require user login permissions to request data, and the server response does not meet expectations, but it cannot be done every time. Each page should be processed separately, so I thought that Axios provides a good thing called interceptor, 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
})

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

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)
 }
)

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)
 }
)

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:

JS summary of array traversal methods and performance comparison

vue select operation component opening

JS operation JSON array deduplication

The above is the detailed content of Encapsulate Vue2 routing navigation hook and use it in actual combat. 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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools