我有这个输入框:
<b-row>
<b-col md="3"
v-for="(header, index) in columns"
:key="index"
>
<b-form-group>
<b-form-input
placeholder="Search"
type="text"
class="d-inline-block"
@input="advanceSearch($event, header.field)"
/>
</b-form-group>
</b-col>
</b-row>
当用户输入内容时,我将输入存储到
searchString
:
advanceSearch(e, field) {
this.searchString.push({
[field] : e
});
// http.post().then().catch(); // my http call
},
我想在用户完成输入后调用http请求。但似乎并不是每个强键都被称为 HTTP。
VUE JS 有什么办法吗?
看起来您希望在闲置打字和用户集中注意力时触发该功能。
未聚焦的输入会触发事件
change
,因此应该很容易使用。您还可以实现去抖,相当于以下内容:
export default {
advanceSearch(e, field) { /* ... */ },
// create a custom debounced search
debouncedSearch(...args) {
clearTimeout(this.debounceTimeout); // if we set a previous debounce timeout, don't fire it
this.debounceTimeout = setTimeout(
// we need to bind a custom `this` value because setTimeout binds `window` by default:
e => this.advanceSearch.apply(this, args),
500 // debounce time
);
},
// ...
}
对于您的 Vue 代码,输入应如下所示。请注意如何将
change
侦听器添加到组件,并且 input
处理程序调用 debounce
函数而不是直接调用。
<b-form-input
placeholder="Search"
type="text"
class="d-inline-block"
@input="debouncedSearch($event, header.field)"
@change="advanceSearch($event, header.field)"
/>
此代码的本质作用是,当用户键入然后单击输入框(“模糊”)时,HTTP 请求将触发,或者当用户暂停键入半秒时(随意更改此值),请求也将被发送。
这就是我如何以最少的代码量实现这一点并且易于使用:
<template>
<input v-model="searchInput" type="text" placeholder="Search...">
</template
<script>
export default {
data() {
return {
searchInput: null
};
},
watch: {
searchInput: function() {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.searchFunction();
}, 500);
}
},
methods: {
searchFunction() {
/* whatever you perform for your search */
// use this.searchInput as search term
},
}
}
</script>
使用
v-model
和 searchInput
避免在每个事件和方法之间传递搜索参数。
500 可以替换为任何你想要的,因为输入结束后搜索延迟,300 到 600 通常对于用户体验来说是可以的。