美文网首页
在vue中使用防抖

在vue中使用防抖

作者: 方_糖 | 来源:发表于2021-03-17 16:47 被阅读0次
1、弄懂一般形式的防抖

参考:https://juejin.cn/post/6895210892641304589

防抖是在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时。
常规写法如下

//html: <input type="text" id="input">
var debounce = function(fn){
    let timeout = null;
    return function(){
        if(timeout){
            clearTimeout(timeout)
        }
        timeout = setTimeout(() => {
            sayHi()
        }, 500)
    }
} 
var sayHi = function(
    console.log("Hi," + document.getElementById("input").value);
}
document.getElementById("input").addEventListener("keyup",debounce(sayHi))
(1)debounce方法中为什么用return function(){}?
  • 因为addEventListener中的debounce(sayHi)是一个立即执行方法,在页面加载时就会执行。如何让 debounce 不执行呢?改写为回调函数即可(使用return function)
//一般的addEventListener写法
xx.addEventListener("click",function(){})
//防抖中addEventListener写法
xx.addEventListener("click",debounce())
(2)为什么把let timeout = null; 写在debouce方法中,而不是写成全局变量?
  • let timeout = null; 也可以写成全局变量。
    但是因为debouce(sayHi)在页面加载时就会主动执行, 所以写在debouce里面可以避免污染全局环境timeout变量在return后的function中的作用域链中,所以写在debounce中更好。
    因此也可以把防抖写成这样
let timeout = null;
var debounce = function(fn){  
    if(timeout){
        clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
        sayHi()
    }, 500)
} 
var sayHi = function(){
    console.log("Hi," + document.getElementById("input").value);
}
document.getElementById("input").addEventListener("keyup",function(){
    debounce(sayHi)
})
2. vue中防抖的写法

由上面改写过来变成:

<template>
    <div> 
        <input v-model="answer" @keyup="change" />
    </div>
</template>
<script>
    export default {
        name: "",
        data() {
            answer: "",
            timeout: null
        },
        method: {
            change() {
                if(this.timeout){
                    clearTimeout(this.timeout)
                }
                this.timeout = setTimeout(() => {
                    console.log(this.answer)
                }, 500);
            }
        }
    }
</script>

相关文章

网友评论

      本文标题:在vue中使用防抖

      本文链接:https://www.haomeiwen.com/subject/cuafqltx.html