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