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,內(nèi)容如下;這是一個輸入框的 500ms 的防抖
<template>
<div class="main">
<el-input v-model="input" @change="changeSeletc" placeholder="請輸入內(nèi)容"></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.效果如下圖