vue实现搜索脚本之家
Vue 实现搜索功能(以脚本之家为例)
核心思路
通过 Vue 的响应式特性绑定搜索关键词,利用计算属性或方法过滤数据,配合事件处理实现实时搜索。
基础实现步骤
数据准备
data() {
return {
searchText: '',
articles: [
{ id: 1, title: 'Vue基础教程', content: '介绍Vue核心概念' },
{ id: 2, title: 'React对比', content: 'Vue和React差异分析' }
]
}
}
模板部分

<div class="search-box">
<input v-model="searchText" placeholder="输入关键词...">
<ul>
<li v-for="item in filteredList" :key="item.id">
{{ item.title }} - {{ item.content }}
</li>
</ul>
</div>
计算属性实现过滤
computed: {
filteredList() {
return this.articles.filter(item =>
item.title.includes(this.searchText) ||
item.content.includes(this.searchText)
)
}
}
增强功能实现
防抖优化

methods: {
search: _.debounce(function() {
this.filteredResults = this.getFilteredData()
}, 300)
}
远程搜索示例
methods: {
async searchRemote() {
const res = await axios.get(`/api/search?q=${this.searchText}`)
this.results = res.data
}
}
高亮匹配文本
filters: {
highlight(text, query) {
return text.replace(
new RegExp(query, 'gi'),
match => `<span class="highlight">${match}</span>`
)
}
}
样式建议
.highlight {
background-color: yellow;
font-weight: bold;
}
.search-box {
max-width: 600px;
margin: 0 auto;
}
input {
width: 100%;
padding: 8px;
}
注意事项
- 敏感词过滤应在服务端完成
- 大量数据建议采用分页加载
- 移动端需优化输入体验
- 考虑添加搜索历史功能

