我在Vue模板中有一个简单的输入框,我想或多或少地使用debounce:
<input type="text" v-model="filterKey" debounce="500">
Run Code Online (Sandbox Code Playgroud)
但是,该debounce物业已在Vue 2中弃用.该建议仅说:"使用v-on:输入+第三方去抖功能".
你是如何正确实现它的?
我试图使用lodash,v-on:input和v-model来实现它,但我想知道是否可以不使用额外的变量.
在模板中:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
Run Code Online (Sandbox Code Playgroud)
在脚本中:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
Run Code Online (Sandbox Code Playgroud)
然后在computed道具中使用filterkey .
我有一个输入框.用户停止输入后,我想执行HTTP请求并等待结果.
由于jsbin上不允许网络请求,我使用了setTimeout().
var log = console.log.bind(console)
var delayedResults = new Promise(function(resolve) {
setTimeout(function(){
resolve('Wooo I am the result!')
}, 3000);
});
document.querySelector('input').addEventListener('input', _.debounce(async function(){
log('Doing search')
var result = await delayedResults
log('Result is', result)
}), 500);
Run Code Online (Sandbox Code Playgroud)
但是,当我在框中输入时,"正在搜索"会立即显示每个字符 - 我希望它仅在500毫秒到期后出现.
我怎样才能使用去抖并等待?
如何debounce在async功能上使用?我的vue-app中有一个方法,该方法可从API检索数据,该方法连续调用该API,而我想避免这种情况。
这是我的方法:
methods: {
async getAlbums () {
const response = await AlbumService.fetchAlbums()
this.albums = response.data.albums
}
}
Run Code Online (Sandbox Code Playgroud)
我以前已经安装了,lodash那么如何实现呢?