最近在做实时搜索功能时,被要求使用防抖函数,就自己手写一个,已用于大型项目中
<template><el-input placeholder="请搜索关键字" @input="inputHandle" v-model="input4"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input></template>export default{data(){timeId: undefined,isLoading: false,input4: ''},methods:{inputHandle(val){this.input4 = val/*以下为防抖代码*/if (!this.timeId && !this.isLoading) {this.guidanceTailList()}if (this.timeId) {clearTimeout(this.timeId)}this.timeId = setTimeout(() => {this.timeId = undefinedclearTimeout(this.timeId)this.guidanceTailList()}, 2500)/*以上为防抖代码*/},guidanceTailList(){this.isLoading=true......省略ajax请求...this.isLoading=false}}}