Vue lodash.debounce防抖函数

Vue 中使用防抖函数

这篇文章也是衔接我之前文章,输入内容延迟显示。

一般防抖函数,一般都是自己写,或者直接搜的类似这种

function debounce(fn,wait){
    var timer = null;
    return function(){
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(fn,wait);
    }
}

Vue官网Demo

https://cn.vuejs.org/v2/guide/computed.html#侦听器

我看到Vue官网 侦听器 使用了lodash这个组件

created: function () { 
// _.debounce 是一个通过 Lodash 限制操作频率的函数。 
// 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率 
// AJAX 请求直到用户输入完毕才会发出。想要了解更多关于 
// _.debounce 函数 (及其近亲 _.throttle) 的知识,
// 请参考:https://lodash.com/docs#debounce
this.debouncedGetAnswer = \_.debounce(this.getAnswer, 500)
}

我就在想既然,官网都不用自己手写的,那我也用一下这个。

lodash.debounce

先看 https://lodash.com/docs#debounce 文档

由于我只用了防抖,所以我只安装防抖函数

npm i --save lodash.debounce

使用


import debounce from 'lodash.debounce'

textChange: debounce(function() {
        //注意这里如果使用箭头函数的话, this为 undefined https://github.com/vue-styleguidist/vue-docgen-api/issues/23
         // do sth
}, 300)

总结

已经有轮子的话,就不要自己造轮子,当然练习的时候可以自己造。

原文地址:https://www.cnblogs.com/CharmCode/p/13423536.html