我有一个过滤器输入字段,并希望筛选一个项目列表。这个列表很大,所以我想要使用delay来延迟应用过滤器,直到用户停止输入以改善用户体验。这是我的输入字段,它绑定到用于筛选列表的filterText。
<input type="text" v-model="state.filterText" />发布于 2020-11-24 16:20:36
我没有找到任何好的解决方案,因为我想看到我的绑定在我的模板,所以我决定分享我的解决方案。我编写了一个简单的and函数,并使用以下语法绑定该行为:
setup() {
...
function createDebounce() {
let timeout = null;
return function (fnc, delayMs) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fnc();
}, delayMs || 500);
};
}
return {
state,
debounce: createDebounce(),
};
},以及模板语法:
<input
type="text"
:value="state.filterText"
@input="debounce(() => { state.filterText = $event.target.value })"
/>发布于 2021-04-03 00:48:55
嗨,第一次在这里回答一些事情,所以请尽量更正我的答案,我会很感激的。我认为最漂亮和最轻的解决方案是创建一个全局指令,您可以在所有表单中使用任意数量的指令。
首先使用指令创建文件,例如。debouncer.js
然后创建一个函数,用于删除
//debouncer.js
/*
This is the typical debouncer function that receives
the "callback" and the time it will wait to emit the event
*/
function debouncer (fn, delay) {
var timeoutID = null
return function () {
clearTimeout(timeoutID)
var args = arguments
var that = this
timeoutID = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
/*
this function receives the element where the directive
will be set in and also the value set in it
if the value has changed then it will rebind the event
it has a default timeout of 500 milliseconds
*/
module.exports = function debounce(el, binding) {
if(binding.value !== binding.oldValue) {
el.oninput = debouncer(function(){
el.dispatchEvent(new Event('change'))
}, parseInt(binding.value) || 500)
}
}定义这个文件之后,您可以转到main.js,导入它并使用导出的函数。
//main.js
import { createApp } from 'vue'
import debounce from './directives/debounce' // file being imported
const app = createApp(App)
//defining the directive
app.directive('debounce', (el,binding) => debounce(el,binding))
app.mount('#app')它完成了,当您想对输入使用指令时,您只需这样做,就不会导入或其他任何东西。
//Component.vue
<input
:placeholder="filter by name"
v-model.lazy="filter.value" v-debounce="400"
/>如果您选择这样做,则v- make . way指令很重要,因为默认情况下,它将更新输入事件上的绑定属性,但是设置它将使它等待更改事件,而这是我们在do函数中发出的事件。这样做将停止v模型自身的更新,直到停止编写或超时(可以在指令的值中设置)。希望这是可以理解的。
发布于 2021-03-14 07:52:21
<template>
<input type="text" :value="name" @input="test" />
<span>{{ name }}</span>
</template><script lang="ts">
import { defineComponent, ref } from 'vue'
function debounce<T> (fn: T, wait: number) {
let timer: ReturnType<typeof setTimeout>
return (event: Event) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
if (typeof fn === 'function') {
fn(event)
}
}, wait)
}
}
export default defineComponent({
setup () {
const name = ref('test')
function setInputValue (event: Event) {
const target = event.target as HTMLInputElement
name.value = target.value
}
const test = debounce(setInputValue, 1000)
return { name, test }
}
})
</script>https://stackoverflow.com/questions/64990541
复制相似问题