1.首先新建一个 debounce.js 代码如下
const debounce=function(fn, delay){
let timer = null
return function(){
let content = this;
let args = arguments;
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(content,args)
}, delay)
}
}
export default debounce
2.在需要防抖的 vue 文件中引入 debounce,内容如下;这是一个输入框的 500ms 的防抖
<template>
<div class="main">
<el-input v-model="input" @change="changeSeletc" placeholder="请输入内容"></el-input>
</div>
</template>
<script>
import debounce from "../utils/debounce"
export default {
name: "alarm",
data(){
return{
input: ''
}
},
methods:{
changeSeletc:debounce(function () {
console.log(this.input)
},500),
}
}
</script>
<style scoped>
</style>
3.效果如下图