vue实现延时触发watch
使用 setTimeout 实现延时触发 watch
在 Vue 中,可以通过 setTimeout 在 watch 中实现延时触发逻辑。这种方法适用于需要在数据变化后延迟执行某些操作的场景。
watch: {
targetValue(newVal, oldVal) {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
this.timeoutId = setTimeout(() => {
// 延时执行的逻辑
console.log('延时触发:', newVal);
}, 500); // 延迟 500 毫秒
}
}
使用 lodash.debounce 实现防抖
通过 lodash 的 debounce 方法可以更简洁地实现延时触发,避免手动管理定时器。
import { debounce } from 'lodash';
export default {
data() {
return {
targetValue: ''
};
},
watch: {
targetValue: debounce(function(newVal) {
// 延时执行的逻辑
console.log('防抖触发:', newVal);
}, 500) // 延迟 500 毫秒
}
};
使用 watch + computed 结合实现延时
如果需要更复杂的逻辑,可以结合 computed 和 watch 实现延时触发。
export default {
data() {
return {
targetValue: '',
delayedValue: ''
};
},
computed: {
computedValue() {
return this.targetValue;
}
},
watch: {
computedValue(newVal) {
setTimeout(() => {
this.delayedValue = newVal;
console.log('延时更新:', this.delayedValue);
}, 500);
}
}
};
使用自定义指令实现延时触发
如果需要复用延时逻辑,可以封装为自定义指令。
Vue.directive('delay', {
bind(el, binding) {
let timeoutId = null;
el.addEventListener('input', () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
binding.value(el.value);
}, binding.arg || 500);
});
}
});
// 使用方式
<input v-delay="handleDelayedInput" v-model="inputValue" />
注意事项
- 清除定时器:使用
setTimeout时,务必在组件销毁前清除未执行的定时器,避免内存泄漏。 - 防抖与节流:根据场景选择防抖(
debounce)或节流(throttle),防抖适用于频繁触发但只需最后一次结果的场景。 - 性能优化:对于高频数据变化(如输入框输入),建议使用防抖或节流减少不必要的计算或请求。







