vue 实现搜索功能
实现搜索功能的基本思路
在Vue中实现搜索功能通常需要结合数据绑定、计算属性和方法。搜索功能的核心是对数据列表进行过滤,根据用户输入的关键词筛选出匹配的项。
基础实现步骤
数据准备 定义一个数据列表和搜索关键词的绑定变量:
data() {
return {
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
],
searchQuery: ''
}
}
计算属性过滤 使用计算属性实现实时搜索过滤:
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
模板绑定 在模板中添加搜索输入框和结果展示:
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
高级搜索功能
多字段搜索 如果需要搜索多个字段,可以扩展过滤逻辑:
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
)
}
}
防抖优化 对于频繁触发的搜索,可以使用防抖技术:
import { debounce } from 'lodash'
methods: {
handleSearch: debounce(function() {
// 执行搜索逻辑
}, 300)
}
服务器端搜索
API调用 当数据量较大时,应该使用后端搜索:
methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.items = response.data
} catch (error) {
console.error(error)
}
}
}
监听搜索词变化 使用watch监听searchQuery变化:
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.searchItems()
}
}
}
用户体验优化
加载状态 添加加载状态提示:
data() {
return {
isLoading: false
}
}
methods: {
async searchItems() {
this.isLoading = true
try {
// API调用
} finally {
this.isLoading = false
}
}
}
空状态提示 在模板中添加空状态提示:
<div v-if="filteredItems.length === 0">
No items found matching "{{ searchQuery }}"
</div>
完整示例代码
<template>
<div>
<input
v-model="searchQuery"
placeholder="Search..."
@input="handleSearch"
>
<div v-if="isLoading">Loading...</div>
<ul v-else>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<div v-if="!isLoading && filteredItems.length === 0">
No results found
</div>
</div>
</template>
<script>
import { debounce } from 'lodash'
export default {
data() {
return {
items: [],
searchQuery: '',
isLoading: false
}
},
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
},
methods: {
handleSearch: debounce(function() {
this.searchItems()
}, 300),
async searchItems() {
if (this.searchQuery.length < 2) return
this.isLoading = true
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.items = response.data
} catch (error) {
console.error(error)
} finally {
this.isLoading = false
}
}
}
}
</script>






