_.debounce 应用

来源:互联网 发布:淘宝客引流方法 编辑:程序博客网 时间:2024/06/05 10:28

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 1
原创粉丝点击