Vue.js新手如何实现搜索框功能 对前端获取的数据进行过滤
Vue前端搜索过滤实现方案
核心思路
用Vue自带的计算属性实现实时过滤,无需手动监听输入事件,代码更简洁高效。
修改步骤
- 调整data结构:新增
search字段绑定搜索输入,新增rawProducts存储全量原始数据 - 新增计算属性
filteredProducts,根据搜索关键词动态返回过滤后的列表 - 替换模板中v-for的遍历对象为过滤后的计算属性
完整修改后代码
<template> <div> <div class="search-wrapper panel-heading col-sm-12"> <input type="text" v-model="search" placeholder="Search" /> <br /> <br /> </div> <table class="table" id="myTable"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Category</th> <th>Quantity</th> <th>Status</th> </tr> </thead> <tbody> <!-- 遍历过滤后的列表 --> <tr v-for="product in filteredProducts" :key="product.id"> <td>{{ product.id }}</td> <td>{{ product.name }}</td> <td>{{ product.category }}</td> <td>{{ product.quantity }}</td> <td>{{ product.status }}</td> </tr> </tbody> </table> </div> </template> <script> export default { data() { return { search: '', // 绑定搜索框输入值 rawProducts: [] // 存储全量原始数据 }; }, computed: { filteredProducts() { // 搜索关键词为空时返回全量数据 if (!this.search.trim()) return this.rawProducts // 统一转小写实现大小写不敏感搜索 const keyword = this.search.trim().toLowerCase() return this.rawProducts.filter(product => { // 可自定义需要匹配的字段,这里匹配所有展示的5个字段 return String(product.id).toLowerCase().includes(keyword) || product.name.toLowerCase().includes(keyword) || product.category.toLowerCase().includes(keyword) || String(product.quantity).toLowerCase().includes(keyword) || product.status.toLowerCase().includes(keyword) }) } }, mounted() { // 示例:从接口获取数据后赋值给rawProducts即可 // 你原来给products赋值的逻辑,改成给rawProducts赋值就行 // 比如 axios.get('/api/products').then(res => this.rawProducts = res.data) } }; </script>
自定义调整说明
- 若只需匹配特定字段,删除filter方法中不需要的匹配逻辑即可
- 若需要精确匹配,将
includes替换为===即可 - 若需要正则匹配搜索,可自行构造正则对象替换现有匹配逻辑
内容的提问来源于stack exchange,提问作者Noobmaster
相关产品推荐
相关产品推荐

