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...

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

created: function () { // _.debounce 是一个通过 Lodash 限度操作频率的函数。 // 在这个例子中,咱们心愿限度拜访 yesno.wtf/api 的频率 // AJAX 申请直到用户输出结束才会收回。想要理解更多对于 // _.debounce 函数 (及其远亲 _.throttle) 的常识,// 请参考:https://lodash.com/docs#debouncethis.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)

总结

曾经有轮子的话,就不要本人造轮子,当然练习的时候能够本人造。