vue实现搜索查询
Vue 实现搜索查询功能
数据绑定与搜索逻辑
-
在 Vue 组件中定义搜索关键词和数据列表
data() { return { searchQuery: '', items: [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Orange' } ] } } -
使用计算属性实现实时过滤
computed: { filteredItems() { return this.items.filter(item => item.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ) } }
模板实现
-
搜索输入框绑定
<input type="text" v-model="searchQuery" placeholder="Search..." > -
显示过滤结果
<ul> <li v-for="item in filteredItems" :key="item.id"> {{ item.name }} </li> </ul>
优化搜索性能
-
添加防抖处理减少频繁计算
import _ from 'lodash' methods: { debouncedSearch: _.debounce(function(query) { this.searchQuery = query }, 300) } -
模板中使用防抖方法
<input @input="debouncedSearch($event.target.value)" >
服务器端搜索实现
-
使用 axios 发起搜索请求
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(newVal) { if (newVal.length > 2) { this.searchItems() } } }
样式增强
-
添加加载状态
data() { return { isLoading: false } } methods: { async searchItems() { this.isLoading = true // ...请求逻辑 this.isLoading = false } } -
模板显示加载状态

<div v-if="isLoading">Searching...</div>






