vue实现搜索表格
Vue 实现搜索表格功能
数据绑定与表格渲染
在 Vue 中通过 v-model 绑定搜索输入框,实时监听用户输入。表格数据使用 v-for 动态渲染,初始数据可从 API 或本地获取。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索..." />
<table>
<tr v-for="item in filteredItems" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.email }}</td>
</tr>
</table>
</div>
</template>
计算属性处理搜索逻辑
利用 Vue 的 computed 属性实现搜索过滤,避免每次输入都触发方法调用。通过 toLowerCase() 统一大小写,提升搜索友好度。
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '张三', email: 'zhang@example.com' },
{ id: 2, name: '李四', email: 'li@example.com' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
item.email.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
样式优化与交互增强
为搜索框添加 debounce 防抖(可使用 lodash 或自定义),减少频繁触发过滤。添加无结果提示,改善用户体验。
<template>
<div>
<input
v-model="searchQuery"
placeholder="搜索..."
class="search-input"
/>
<table v-if="filteredItems.length">
<!-- 表格内容 -->
</table>
<p v-else>未找到匹配结果</p>
</div>
</template>
<style>
.search-input {
padding: 8px;
margin-bottom: 16px;
width: 300px;
}
</style>
服务端搜索集成(可选)
对于大数据量场景,可将搜索逻辑移至服务端。通过 watch 监听 searchQuery 变化,发起 API 请求获取过滤后的数据。
<script>
export default {
watch: {
searchQuery(newVal) {
this.fetchFilteredData(newVal)
}
},
methods: {
async fetchFilteredData(query) {
const res = await axios.get('/api/items', { params: { q: query } })
this.filteredItems = res.data
}
}
}
</script>






