_.debounce 应用

4 篇文章 0 订阅

1,定义。

 如果用手指一直按住一个弹簧,它将不会弹起直到你松手为止。

也就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间。(空闲时间大于,设定的时间是才会执行!!!)

eg:

<div id="watch-example" style="font-size: 50px">
    <p>
        Ask a yes/no question:
        <input v-model="question">
    </p>
    <p>{{ answer }}</p>
</div>

var watchExampleVM = new Vue({
    el: '#watch-example',
    data: {
        question: '',
        answer: 'I cannot give you an answer until you ask a question!'
    },
    watch: {
        // 如果 question 发生改变,这个函数就会运行
        question: function (newQuestion) {
            this.answer = 'Waiting for you to stop typing...'
            this.getAnswer()
        }
    },
    methods: {
        // _.debounce 是一个通过 lodash 限制操作频率的函数。
        // 在这个例子中,我们希望限制访问yesno.wtf/api的频率
        // ajax请求直到用户输入完毕才会发出
        //参考: https://lodash.com/docs#debounce
        getAnswer: _.debounce(
                function () {
                    var vm = this
                    if (this.question.indexOf('?') === -1) {
                        console.log('ttt')
                        vm.answer = 'Questions usually contain a question mark. ;-)'
                        return
                    }
                    vm.answer = 'Thinking...'
                    axios.get('https://yesno.wtf/api')
                            .then(function (response) {
                                vm.answer = _.capitalize(response.data.answer)
                            })
                            .catch(function (error) {
                                vm.answer = 'Error! Could not reach the API. ' + error
                            })
                },
                // 这是我们为用户停止输入等待的毫秒数
               500
        )
    }
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值