You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js新手如何实现搜索框功能 对前端获取的数据进行过滤

Vue前端搜索过滤实现方案

核心思路

用Vue自带的计算属性实现实时过滤,无需手动监听输入事件,代码更简洁高效。

修改步骤

  1. 调整data结构:新增search字段绑定搜索输入,新增rawProducts存储全量原始数据
  2. 新增计算属性filteredProducts,根据搜索关键词动态返回过滤后的列表
  3. 替换模板中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:09:01