防抖
概念:避免在短时间内重复触发同一个事件
依赖安装npm i lodash
导入import _ from 'lodash’
代码示例:
1 2 3 4 5 6 7 8
| const fun= (str)=>{ console.log(str); }
const fun1 = _.debounce(fun,500)
|
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({ 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, }) }
|