vue,输入input 延迟1秒再调用方法
在 Vue 中,你可以结合 v-model
和 Vue 的计算属性或侦听器来实现输入延迟触发的功能。以下是使用侦听器的一个示例:
<template>
<input type="text" v-model="inputValue">
</template>
<script>
import { ref, watch } from 'vue';
export default {
setup() {
const inputValue = ref('');
watch(inputValue, (newValue, oldValue) => {
if (newValue !== oldValue) {
setTimeout(() => {
// 在这里调用你的方法
console.log(`Input value after delay: ${newValue}`);
}, 1000);
}
});
return {
inputValue,
};
},
};
</script>
在这个示例中,我们使用了 Vue 3 的 Composition API。首先,我们引入了 ref
和 watch
。然后,我们定义了一个响应式引用 inputValue
并用 v-model
将其绑定到 input 元素。
接着,我们使用 watch
函数来侦听 inputValue
的变化。当 inputValue
改变时,watch
会调用我们提供的回调函数。在这个回调函数中,我们使用 setTimeout
来实现延迟效果:只有在用户输入1秒后,才会打印新的 inputValue
。
请注意,如果用户在1秒内连续输入,那么每次输入都会设置一个新的定时器,可能会导致多次调用回调函数。如果你想要避免这种情况,你需要清除上一个定时器,这就需要更复杂的逻辑,例如使用防抖函数。