vue实现搜索列表
Vue 实现搜索列表功能
在 Vue 中实现搜索列表功能通常需要以下几个关键步骤:
数据绑定与列表渲染
使用 v-model 绑定搜索输入框,监听用户输入。通过 v-for 指令渲染过滤后的列表数据。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredList" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
计算属性处理搜索逻辑 利用 Vue 的计算属性实时过滤列表数据,避免直接修改原始数据。
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredList() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
优化搜索性能 对于大型数据集,可以添加防抖函数减少频繁计算。
methods: {
debounceSearch: _.debounce(function() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}, 300)
}
样式美化 添加基础样式提升用户体验,如高亮匹配文本、加载状态等。
<style>
.highlight {
background-color: yellow;
}
</style>
API 集成
如需从后端获取数据,可在 mounted 钩子中调用 API。
async mounted() {
try {
const response = await axios.get('/api/items')
this.items = response.data
} catch (error) {
console.error(error)
}
}
高级实现方案
使用 Vuex 管理状态 当搜索功能涉及多个组件时,建议使用 Vuex 集中管理状态。
// store.js
state: {
searchQuery: '',
allItems: []
},
getters: {
filteredItems: state => {
return state.allItems.filter(item =>
item.name.includes(state.searchQuery)
)
}
}
添加分页功能 长列表可结合分页组件提升性能。
<pagination
:total-items="filteredList.length"
@page-changed="handlePageChange"
/>
本地存储搜索历史
使用 localStorage 保存用户搜索记录。
watch: {
searchQuery(newVal) {
if (newVal) {
this.saveToHistory(newVal)
}
}
}






