vue 实现搜索联想
实现搜索联想功能
在Vue中实现搜索联想功能,可以通过监听输入框的变化,实时发送请求获取匹配的联想词。以下是具体实现方法:
监听输入框变化
使用v-model绑定输入框的值,并通过watch或@input事件监听输入变化。

<template>
<div>
<input
v-model="searchQuery"
@input="handleInput"
placeholder="输入搜索内容"
/>
<ul v-if="suggestions.length">
<li
v-for="(suggestion, index) in suggestions"
:key="index"
@click="selectSuggestion(suggestion)"
>
{{ suggestion }}
</li>
</ul>
</div>
</template>
防抖处理
为了避免频繁发送请求,可以使用防抖函数(如lodash.debounce)控制请求频率。

import { debounce } from 'lodash';
export default {
data() {
return {
searchQuery: '',
suggestions: []
};
},
methods: {
handleInput: debounce(function() {
if (this.searchQuery.trim() === '') {
this.suggestions = [];
return;
}
this.fetchSuggestions();
}, 300),
async fetchSuggestions() {
try {
const response = await axios.get('/api/suggestions', {
params: { query: this.searchQuery }
});
this.suggestions = response.data;
} catch (error) {
console.error('获取联想词失败:', error);
}
},
selectSuggestion(suggestion) {
this.searchQuery = suggestion;
this.suggestions = [];
}
}
};
后端接口实现
后端需要提供一个接口,根据输入的关键词返回匹配的联想词。例如:
// Node.js 示例
app.get('/api/suggestions', (req, res) => {
const query = req.query.query.toLowerCase();
const suggestions = ['apple', 'banana', 'cherry'].filter(item =>
item.toLowerCase().includes(query)
);
res.json(suggestions);
});
高亮匹配部分
如果需要高亮显示匹配部分,可以使用v-html和正则表达式。
<li
v-for="(suggestion, index) in suggestions"
:key="index"
@click="selectSuggestion(suggestion)"
v-html="highlightMatch(suggestion)"
></li>
methods: {
highlightMatch(suggestion) {
const regex = new RegExp(this.searchQuery, 'gi');
return suggestion.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
}
}
.highlight {
color: #42b983;
font-weight: bold;
}
注意事项
- 性能优化:防抖时间不宜过长或过短,通常300ms左右。
- 空值处理:输入为空时清空联想列表。
- 错误处理:捕获并处理请求异常。
- 安全性:使用
v-html时注意防范XSS攻击。
通过以上方法,可以高效实现Vue中的搜索联想功能。






