How to encapsulate Vue2 route navigation hook and axios interceptor
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 require2. Specific requirements
- User authentication and redirection: use the routing navigation hook provided by Vue
- Request data serialization: use the request interceptor provided by axios
- 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 levelAll configurations of routing and navigation hooks are in router/index.js, here It’s part of the codeimport 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 routerAt 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:
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)