And*_*ter 1 javascript settimeout vue.js vuejs2 nuxt.js
我的应用程序中的搜索字段有自定义观察程序:
watch: {
search (query) {
if(query.length > 2) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,search在我的例子中,我已经在 var 的每次更改值时向服务器发送了请求。我厌倦了将代码粘贴到里面setTimeout,但是当用户输入 3 次时,请求也发送了 3 次而不是一次。我需要在用户键入时等待,并在停止键入后向服务器发送一个请求。
setTimeout(function () {
// request code here
}, 3000);
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 vue.js 观察者中正确地做到这一点?
您可以debounce在lodash中使用。它非常适合您的用例。
import _ from lodash
watch: {
search (query) {
this.performSearch(query)
}
},
methods: {
performSearch: _.debounce(function(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}, 200)
}
Run Code Online (Sandbox Code Playgroud)
如果你想在没有lodash库的情况下实现它,你可以尝试
data() {
return {
timeoutQuery: null
}
},
watch: {
search (query) {
if (this.timeoutQuery) { clearTimeout(this.timeoutQuery) }
this.timeoutQuery = setTimeout(() => this.performSearch(query), 300)
}
},
methods: {
performSearch(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}
Run Code Online (Sandbox Code Playgroud)