当用户在Vue.js的搜索字段中键入完一些文本时,我应该使用哪个事件来做出反应



我有一个文本字段(取自vuetify库(,用于过滤应用程序中的一些表。

<v-text-field
style="min-width: 300px;"
v-model="filterString"
label="Search" />

工作原理很简单——每次用户提供新的筛选值时,都应该更新表内容。没有提交按钮或类似的东西。过滤是在后端实现的,所以每次更新都需要向我的API发送一个请求。当过滤器字符串更新时,我使用Vue.js观察程序发送请求。

watch: {
async filterString() {
// some logic containing communication with my api
},
},

假设我的应用程序的用户在搜索框中键入了大约10个字母的字符串。然后,我的应用程序向API发送10个请求,忽略了前9个请求是无用的。这就是我的问题。我应该使用时钟,并且只有在经过一定时间后才发送请求吗?当用户完成键入时,是否有一些事件被触发,我需要订阅?如何仅当用户在我的框中完成键入时才发送请求?谢谢你的回答。

您正在寻找的是所谓的去抖动。它只是一个计时器,等待你停止按键。

这里有一个使用lodash去抖动的快速方法

模板:

<input
:value="input"
@change="evt=>textChange(evt.target.value)"
@input="evt=>textEntry(evt.target.value)"               
/>

javascript:

进口:

import { debounce } from 'lodash'

定义:

model: {
prop: 'input',
event: 'input'
},
props: {
input: {
default: '',
type: String
},
debounce: {
default: -1,
type: Number
}
},
methods: {
textChange (value) {
this.$emit('input', value)
}
},
textEntry (value) {
// This is to cover for situations where the change event runs first
if (value.toUpperCase() === this.input.toUpperCase()) return
if (this.debounce >= 0) {
this.emitValue(value)
} else {
this.$emit('input', value)
}
}
},
async mounted () {
this.emitValue = debounce(value => {
this.$emit('input', value)
}, Math.abs(this.debounce))
await this.$nextTick()
this.textChange(this.input) // apply whatever was loaded, and allow bindings to run
}

您仍然可以将@changeVuetify事件与去抖动工具结合使用。这将阻止您执行多个";无用的";正如你所说。

您可以:

  • 使用像这样的npm包
  • 自己动手(如果你需要帮助,可以看看这个帖子(

相关内容

最新更新