vue实现搜索
Vue 实现搜索功能
在 Vue 中实现搜索功能通常需要结合数据绑定、计算属性和方法。以下是一个完整的实现方案:
基础实现
创建搜索输入框和结果列表:
<template>
<div>
<input v-model="searchQuery" 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: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
高级实现
添加防抖优化性能:
import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: '',
filteredItems: []
}
},
watch: {
searchQuery: debounce(function(newVal) {
this.filterItems(newVal)
}, 300)
},
methods: {
filterItems(query) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
}
服务器端搜索
使用axios进行API请求:
import axios from 'axios'
export default {
methods: {
async search() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error('搜索失败:', error)
}
}
}
}
UI优化
添加加载状态和空状态提示:
<template>
<div>
<input
v-model="searchQuery"
@input="search"
placeholder="搜索..."
/>
<div v-if="isLoading">加载中...</div>
<div v-else-if="!results.length">没有找到结果</div>
<ul v-else>
<li v-for="result in results" :key="result.id">
{{ result.name }}
</li>
</ul>
</div>
</template>
这些方法可以根据具体需求进行组合和调整,构建出适合不同场景的搜索功能。







