vue实现热搜框
Vue 实现热搜框
基本结构
热搜框通常由输入框和下拉建议列表组成。使用 Vue 的 v-model 实现数据绑定,v-for 渲染建议列表。
<template>
<div class="search-container">
<input
v-model="searchQuery"
@input="handleInput"
placeholder="搜索..."
/>
<ul v-if="showSuggestions" class="suggestions">
<li
v-for="(item, index) in suggestions"
:key="index"
@click="selectSuggestion(item)"
>
{{ item }}
</li>
</ul>
</div>
</template>
数据与逻辑
定义搜索查询、建议列表和显示状态的响应式数据,通过输入事件触发建议更新。

<script>
export default {
data() {
return {
searchQuery: '',
suggestions: [],
showSuggestions: false,
hotKeywords: ['Vue3', 'React', 'JavaScript', 'TypeScript'] // 模拟热搜数据
}
},
methods: {
handleInput() {
if (this.searchQuery) {
// 模拟筛选逻辑,实际可替换为API请求
this.suggestions = this.hotKeywords.filter(keyword =>
keyword.toLowerCase().includes(this.searchQuery.toLowerCase())
);
this.showSuggestions = this.suggestions.length > 0;
} else {
this.showSuggestions = false;
}
},
selectSuggestion(item) {
this.searchQuery = item;
this.showSuggestions = false;
// 触发搜索操作
this.$emit('search', item);
}
}
}
</script>
样式设计
为输入框和下拉列表添加基础样式,确保视觉层次清晰。
<style scoped>
.search-container {
position: relative;
width: 300px;
}
input {
width: 100%;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
}
.suggestions {
position: absolute;
width: 100%;
margin-top: 4px;
padding: 0;
list-style: none;
background: white;
border: 1px solid #eee;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.suggestions li {
padding: 8px 12px;
cursor: pointer;
}
.suggestions li:hover {
background: #f5f5f5;
}
</style>
动态热搜数据
通过 API 获取实时热搜数据,使用 mounted 钩子初始化数据。

<script>
export default {
// ...其他代码
async mounted() {
try {
const response = await fetch('https://api.example.com/hot-keywords');
this.hotKeywords = await response.json();
} catch (error) {
console.error('获取热搜失败:', error);
}
}
}
</script>
防抖优化
避免频繁触发搜索建议,使用 Lodash 的 debounce 函数。
import { debounce } from 'lodash';
export default {
created() {
this.debouncedHandleInput = debounce(this.handleInput, 300);
},
methods: {
handleInput: debounce(function() {
// 原有逻辑
}, 300)
}
}
键盘导航
支持键盘上下箭头选择建议项,增强用户体验。
methods: {
handleKeyDown(event) {
if (!this.showSuggestions) return;
if (event.key === 'ArrowDown') {
// 向下选择逻辑
} else if (event.key === 'ArrowUp') {
// 向上选择逻辑
} else if (event.key === 'Enter') {
// 确认选择
}
}
}






