vue实现搜索框查询
Vue实现搜索框查询的方法
数据绑定与v-model
在Vue中实现搜索功能,通常使用v-model指令实现输入框与数据的双向绑定。在组件的data中定义搜索关键词和结果列表:
data() {
return {
searchQuery: '',
items: [
{ name: 'Apple' },
{ name: 'Banana' },
{ name: 'Cherry' }
]
}
}
模板中使用v-model绑定输入框:
<input v-model="searchQuery" placeholder="Search...">
计算属性过滤
使用计算属性computed实时过滤数据,避免每次输入都手动触发搜索:
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
方法触发搜索
对于需要手动触发的搜索(如点击按钮),可使用方法:
methods: {
performSearch() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
模板中添加按钮:
<button @click="performSearch">Search</button>
防抖优化
频繁输入时通过防抖(debounce)减少计算次数,使用lodash.debounce:
import debounce from 'lodash.debounce'
methods: {
debouncedSearch: debounce(function() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}, 300)
}
输入框监听输入事件:
<input v-model="searchQuery" @input="debouncedSearch">
服务端搜索
若数据量较大,需通过API请求服务端搜索:
methods: {
async fetchSearchResults() {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
}
}
添加监听器触发搜索:
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.fetchSearchResults()
}
}
}
样式与交互优化
添加加载状态和空结果提示:
data() {
return {
isLoading: false,
noResults: false
}
}
methods: {
async fetchSearchResults() {
this.isLoading = true
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
this.noResults = this.results.length === 0
} finally {
this.isLoading = false
}
}
}
模板中显示状态:
<div v-if="isLoading">Loading...</div>
<div v-else-if="noResults">No results found</div>






