javascript - vue js如何延迟发送数据?

标签 javascript vue.js

每次我使用输入时,我的函数都会将数据发送到服务器并得到响应,但如果我想在“名称”字段中写入 - 托马斯·爱迪生,我将逐个字母发送

我尝试放置 setTimeout 函数,如果用户仍然编写字符串,则不会发送任何内容,但我不起作用

 @input="throttledSave"
  throttledSave (e) {
                let eva = e 
                let DELAY = 2000;
                if(e.target.value){
                    return this.throttle(this.setDataFinalJSON, DELAY, eva);
                }
            },

     throttle: function (callback, limit,eva) {
            var wait = false;
            var typingTimer;
            return function (callback, limit,eva) {
                clearTimeout(typingTimer)
                if (!wait) {
                    callback(eva);
                    wait = true;
                    typingTimer = setTimeout(function () {
                        console.log('oh again')
                        wait = false;
                    }, limit);
                }
            }
        }

每次它都工作直到延迟,我不知道为什么,也许clearTimeout不起作用,我被卡住了。我不知道为什么如果我写得这么快,我会得到 console.log('哦,又来了')

最佳答案

您可以使用 lodash debounce ( https://lodash.com/docs/4.17.15#debounce ) 方法来做到这一点:

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

_.debounce(func, [wait=0], [options={}])

示例:

methods: {
    throttledMethod: _.debounce(() => {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }

最好使用 lodash 的 vue 变体:https://www.npmjs.com/package/vue-lodash

关于javascript - vue js如何延迟发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241278/

相关文章:

javascript - 加速这个(基本的)node.js 服务器

jquery - Uncaught ReferenceError : $ is not defined (VueJS)

vue.js - Apexcharts 中 dataPointSelection 事件的返回值

javascript - 弹跳可拖动球

javascript - 使用 wookmark 创建两行

javascript - Angular Controller 生命周期和事件处理

vue.js - Vue CLI - vue 添加 pwa 导致 TypeError : Cannot read properties of undefined (reading 'tapAsync' ) error

vue.js - 如何从 NuxtJS 中的 fetch 或 asyncData 钩子(Hook)访问 vuex 存储?

javascript - 尝试使用 axios 和 formData 发布数据,但它是空的

javascript - jQuery 和动态 ID