vue实现搜索推荐
Vue 实现搜索推荐的方法
使用 v-model 绑定输入框
在 Vue 中,可以通过 v-model 指令双向绑定输入框的值,实时监听用户的输入变化。例如:
<input v-model="searchQuery" @input="handleInput" />
监听输入事件触发搜索
在 handleInput 方法中,可以处理用户的输入,触发搜索推荐逻辑。例如:
methods: {
handleInput() {
if (this.searchQuery.length > 2) {
this.fetchSuggestions();
}
}
}
调用 API 获取推荐数据
通过异步请求从后端 API 获取搜索推荐数据。可以使用 axios 或其他 HTTP 客户端库:
methods: {
fetchSuggestions() {
axios.get('/api/suggestions', { params: { q: this.searchQuery } })
.then(response => {
this.suggestions = response.data;
})
.catch(error => {
console.error(error);
});
}
}
展示推荐列表
将获取到的推荐数据渲染到页面上,通常使用 v-for 指令循环展示:
<ul v-if="suggestions.length">
<li v-for="suggestion in suggestions" :key="suggestion.id">
{{ suggestion.text }}
</li>
</ul>
添加防抖优化性能
为了避免频繁触发 API 请求,可以使用防抖函数优化性能:
import { debounce } from 'lodash';
methods: {
handleInput: debounce(function() {
if (this.searchQuery.length > 2) {
this.fetchSuggestions();
}
}, 300)
}
高亮匹配关键词
在展示推荐结果时,可以高亮显示与用户输入匹配的部分:
<li v-for="suggestion in suggestions" :key="suggestion.id" v-html="highlightMatch(suggestion.text)"></li>
methods: {
highlightMatch(text) {
const regex = new RegExp(this.searchQuery, 'gi');
return text.replace(regex, match => `<strong>${match}</strong>`);
}
}
处理键盘导航
为了方便用户使用键盘导航推荐列表,可以添加键盘事件处理:
<ul v-if="suggestions.length" @keydown.up="handleKeyUp" @keydown.down="handleKeyDown">
<li v-for="(suggestion, index) in suggestions"
:key="suggestion.id"
:class="{ active: index === activeIndex }"
@click="selectSuggestion(suggestion)">
{{ suggestion.text }}
</li>
</ul>
data() {
return {
activeIndex: -1
};
},
methods: {
handleKeyUp() {
if (this.activeIndex > 0) {
this.activeIndex--;
}
},
handleKeyDown() {
if (this.activeIndex < this.suggestions.length - 1) {
this.activeIndex++;
}
},
selectSuggestion(suggestion) {
this.searchQuery = suggestion.text;
this.suggestions = [];
}
}






