面试题答案
一键面试1. 在Vue中实现防抖搜索功能的代码示例
<template>
<div>
<input v-model="searchText" @input="debouncedSearch" placeholder="请输入搜索内容">
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
timer: null
};
},
methods: {
search() {
// 实际的搜索请求逻辑,例如调用API
console.log('执行搜索,搜索内容为:', this.searchText);
},
debouncedSearch() {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.search();
}, 300); // 防抖时间设置为300毫秒
}
}
};
</script>
2. 防抖函数内部原理
防抖的原理是:在事件被触发n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。
- 具体过程:
- 当用户在搜索框输入内容时,每次
input
事件触发都会调用debouncedSearch
方法。 - 在
debouncedSearch
方法中,首先使用clearTimeout(this.timer)
清除之前设置的定时器(如果有的话)。这是因为如果用户持续输入,每次输入都要取消上一次未执行的定时器,防止上一次的搜索请求在用户还未停止输入时就发出。 - 然后使用
setTimeout
设置一个新的定时器,延迟300毫秒(这里设置的时间可以根据实际需求调整)后执行search
方法,search
方法中包含实际的搜索请求逻辑。这样,只有当用户停止输入300毫秒后,才会真正触发搜索请求,避免了频繁请求。
- 当用户在搜索框输入内容时,每次