Vue + Axios global interface anti-shake, throttling package implementation, making your front-end development more efficient

cover.png

Have you ever had such an experience that whenever you use in front-end development Ajaxto make data requests, the page often sends requests continuously due to some wrong operations, and even causes the system to crash? To solve this problem, we need to debounce and throttle the interface.

This article will introduce how to use Vueand Axiosto perform anti-shake and throttling processing on the interface, and introduce its implementation principle and precautions in detail. let's start!

What are interface anti-shake and throttling?

Interface anti-shake and throttling are one of the important components of the website performance optimization solution. In simple terms, anti-shake means to execute a function only once in a certain period of time, while throttling means to execute a function only once in a certain period of time.

In front-end development, network requests and server load can be effectively reduced through interface anti-shake and throttling. By writing anti-shake and throttling code, you can ensure that the front-end page does not have too many requests, so that the web page loads faster and responds more sensitively.

Vue + Axios encapsulates global interface anti-shake and throttling configuration

In Vue, you can encapsulate interface requests by creating a global axiosinstance . Next, we will write axiosexamples to realize anti-shake and throttling functions.

anti shake

Before implementing anti-shake, let's first introduce what "anti-shake" is. In front-end development, "anti-shake" refers to an event that can only be triggered once within a certain period of time, usually an input box or a scroll event. If there is no anti-shake control, some abnormal situations will appear on the page, such as: the search box is entered too fast, the scroll bar jumps frequently, etc.

Realization principle

The implementation principle of anti-shake is very simple, which is to control the number of function executions by delaying the function to be executed. The specific process is as follows:

  1. Define a variable to hold the timer.
  2. Determine whether the timer exists before the function is executed, and clear the timer if it exists.
  3. Set a time delay for the function, saving the return result in a timer variable.
  4. After the waiting time exceeds the set threshold, execute the corresponding callback function.

Here's an example of the anti-shake code:

// 防抖
function debounce(fn, delay = 500) {
  let timer = null;
  return function(...args) {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}
复制代码

Precautions

When using anti-shake technology, you need to pay attention to the following points:

  1. The time delay needs to be adjusted according to business needs.
  2. During the anti-shake process, make sure that the function parameters are passed correctly.

throttling

相比于防抖技术,节流技术更加灵活。在前端开发中,“节流”通常指的是在一定时间内只能执行一次事件,例如:下拉加载更多、页面滚动等。

实现原理

节流技术的实现原理也非常简单,就是通过设置一个固定时间间隔,在这个时间间隔内只能执行一次相应的回调函数。具体流程如下:

  1. 定义一个变量用于保存上一次执行函数的时间。
  2. 在执行函数前获取当前的时间戳。
  3. 判断当前时间与上一次执行时间是否大于设定的间隔时间,如果大于,则执行相应的回调函数,并更新上一次执行时间。
  4. 如果小于设定的间隔时间,则等待下一次执行。

下面是节流代码的示例:

// 节流
function throttle(fn, delay = 500) {
  let last = 0;
  return function(...args) {
    let now = new Date().getTime();
    if (now - last > delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}
复制代码

注意事项

在使用节流技术的时候,需要注意以下几点:

  1. 时间间隔需要根据业务需求进行调整。
  2. 在节流过程中,要确保函数参数传递正确。
  3. 节流过程中可能会出现滞后或者丢失部分事件的问题,需要进行相应的处理。

封装axios实例

在 Vue 中,可以通过创建一个全局的 axios 实例来封装接口请求。下面我们将根据需求,对 axios 实例进行编写,实现防抖和节流功能。

首先,我们需要安装 axios 插件:

npm install axios --save
复制代码

然后,在 main.js 中添加以下代码:

import Vue from 'vue'
import axios from 'axios'

Vue.prototype.$http = axios
复制代码

接下来,我们将编写一个封装函数,用于通过 axios 实例对接口进行防抖和节流处理。

防抖处理

在防抖处理中,我们需要考虑以下几个方面:

  1. 将 axios 实例封装为一个函数。
  2. 在函数调用时进行防抖处理。

下面是封装 axios 实例的示例代码:

import axios from 'axios'

function request(config) {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 10000
  })

  // 防抖
  const debounceTokenCancel = new Map()
  instance.interceptors.request.use(config => {
    const tokenKey = `${config.method}-${config.url}`
    const cancel = debounceTokenCancel.get(tokenKey)
    if (cancel) {
      cancel()
    }
    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

  instance.interceptors.response.use(response => {
    return response
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

  return instance(config)
}

export default request
复制代码

在上述代码中,我们创建了一个 axios 实例,并对该实例进行了防抖处理。其中,debounceTokenCancel 变量用于保存每个请求的计时器对象。在拦截器中,我们通过判断 debounceTokenCancel 中是否存在相应的 key,来决定是否清除计时器和重新设置计时器。

节流处理

在节流处理中,我们需要考虑以下几个方面:

  1. 将 axios 实例封装为一个函数。
  2. 在函数调用时进行节流处理。

下面是封装 axios 实例的示例代码:

import axios from 'axios'

function request(config) {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 10000
  })

  // 节流
  let lastTime = new Date().getTime()
  instance.interceptors.request.use(config => {
    const nowTime = new Date().getTime()
    if (nowTime - lastTime < 1000) {
      return Promise.reject(new Error('节流处理中,稍后再试'))
    }
    lastTime = nowTime
    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

  instance.interceptors.response.use(response => {
    return response
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

  return instance(config)
}

export default request
复制代码

In the above code, we create an instance of axios and throttle the instance. Among them, lastTimethe variable is used to save the time of the last request. In the interceptor, we decide whether to throttle by comparing the current time with the time of the last request.

a complete example

Here is a complete sample code, including anti-shake and throttling:

import axios from 'axios'

function request(config) {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 10000
  })

// 防抖
const debounceTokenCancel = new Map()
instance.interceptors.request.use(config => {
  const tokenKey = `${config.method}-${config.url}`
  const cancel = debounceTokenCancel.get(tokenKey)
  if (cancel) {
    cancel()
  }
  return new Promise(resolve => {
    const timer = setTimeout(() => {
      clearTimeout(timer)
      resolve(config)
    }, 800)
    debounceTokenCancel.set(tokenKey, () => {
      clearTimeout(timer)
      resolve(new Error('取消请求'))
    })
  })
}, error => {
  console.log(error)
  return Promise.reject(error)
})

instance.interceptors.response.use(response => {
  return response
}, error => {
  console.log(error)
  return Promise.reject(error)
})

// 节流
let lastTime = new Date().getTime()
instance.interceptors.request.use(config => {
  const nowTime = new Date().getTime()
  if (nowTime - lastTime < 1000) {
    return Promise.reject(new Error('节流处理中,稍后再试'))
  }
  lastTime = nowTime
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})

return instance(config)
}

export default request
复制代码

In the above code, we create an axios instance, and debounce and throttle the instance. Among them, debounceTokenCancelthe variable is used to save the timer object of each request; lastTimethe variable is used to save the time of the last request.

in conclusion

In front-end development, anti-shake and throttling processing on the interface can effectively reduce network requests and server load, and improve website performance. In this article, we introduced how to use Vue and Axios to anti-shake and throttle the interface, and introduced the implementation principle and precautions in detail. I hope this article can help you better complete your development work.

Guess you like

Origin juejin.im/post/7225133152490160187