防抖

概念:避免在短时间内重复触发同一个事件

依赖安装npm i lodash

导入import _ from 'lodash’

代码示例:

1
2
3
4
5
6
7
8
//随便定义一个函数:
const fun= (str)=>{
console.log(str);
}
//声明一个debounce变量
const fun1 = _.debounce(fun,500)
//其中,fun是一个函数,在fun1的声明中fun不带参数,此后,就把 fun1当fan用
//如:<button @click="fun1('11111')"></button>

axios取消请求

概念:当用户需频繁发送请求,并且新请求的数据会覆盖旧请求时,应该在新请求发送时取消旧请求

axios仓库页面:axios/axios: Promise based HTTP client for the browser and node.js (github.com),取消为Cancellation部分

底层原理挺复杂的(原理讲解见这次终于弄懂Axios是如何中断请求了),但实际用起来很简单。只需new 一个AbortController实例后,在要取消请求时调用这个实例的abort方法即可。

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//请求控制器
const controller = ref(new AbortController())

//关联搜索框
const handleInputList = (val) => {
//取消旧请求
controller.value.abort()
//创建新控制器
controller.value = new AbortController()
//getMatchJobLists是一个封装了的axios方法,将controller.value.signal作为参数传入
getMatchJobLists({ job: val, isSearch: 1 }, controller.value.signal).then((res) => {
isInputSearchArr.value = []
let industry = ""
let direction = ""
if (res.code === 200) {
res.data.forEach((item) => {
if (item.industry) {
industry = item.industry
}

item.direction.forEach((item2) => {
if (item2.direction) {
direction = item2.direction
}

item2.jobs.forEach((item3) => {
isInputSearchArr.value.push({
id: item3.id,
name: item3.name,
industry,
direction,
})
})
})
})
}
})
}

该示例是一个类似浏览器的搜索下拉框,用户每次输入后都向服务器请求用户搜索的内容 ,用户打字较快的话,会在短时间内进行多次请求,而其中只有最后一次请求的结果有意义,因此可以通过取消之前的请求来提升性能。

代码段中的getMatchJobLists是一个封装了的axios方法,其定义如下:

1
2
3
4
5
6
7
8
const getMatchJobLists = (params: any, signal: GenericAbortSignal): any => {
return request({
url: `/match_job_lists`,
method: "get",
signal,
params,
})
}