vue搜索框功能实现
Vue 搜索框功能实现
基础搜索框实现
创建一个基础的搜索框需要绑定输入框的值到 Vue 的数据属性,并通过事件监听触发搜索逻辑。
<template>
<div>
<input
v-model="searchQuery"
@input="handleSearch"
placeholder="输入搜索内容..."
/>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
],
filteredItems: []
}
},
methods: {
handleSearch() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
created() {
this.filteredItems = this.items
}
}
</script>
防抖优化
频繁触发搜索会影响性能,可以通过防抖(debounce)技术优化。

import { debounce } from 'lodash'
export default {
methods: {
handleSearch: debounce(function() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}, 300)
}
}
异步搜索
当需要从 API 获取搜索结果时,可以使用异步方法。
export default {
methods: {
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error('搜索失败:', error)
}
}
}
}
高级搜索功能
实现多条件搜索可以扩展搜索逻辑。

export default {
data() {
return {
searchOptions: {
name: '',
category: '',
priceRange: [0, 100]
}
}
},
methods: {
handleAdvancedSearch() {
this.filteredItems = this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(
this.searchOptions.name.toLowerCase()
)
const categoryMatch = item.category === this.searchOptions.category
const priceMatch = item.price >= this.searchOptions.priceRange[0] &&
item.price <= this.searchOptions.priceRange[1]
return nameMatch && categoryMatch && priceMatch
})
}
}
}
搜索历史记录
添加搜索历史功能可以提升用户体验。
export default {
data() {
return {
searchHistory: []
}
},
methods: {
handleSearch() {
if (this.searchQuery.trim()) {
this.searchHistory.unshift(this.searchQuery)
if (this.searchHistory.length > 5) {
this.searchHistory.pop()
}
}
// 其他搜索逻辑...
}
}
}
样式优化
为搜索框添加样式可以改善视觉效果。
<template>
<div class="search-container">
<input
class="search-input"
v-model="searchQuery"
@input="handleSearch"
placeholder="输入搜索内容..."
/>
<div class="search-results">
<!-- 搜索结果展示 -->
</div>
</div>
</template>
<style>
.search-container {
position: relative;
width: 300px;
margin: 20px auto;
}
.search-input {
width: 100%;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 20px;
outline: none;
}
.search-input:focus {
border-color: #42b983;
}
.search-results {
margin-top: 10px;
border: 1px solid #eee;
border-radius: 5px;
max-height: 300px;
overflow-y: auto;
}
</style>
这些方法涵盖了从基础到高级的 Vue 搜索框实现方式,可以根据实际需求选择适合的方案或组合使用。






