You need to enable JavaScript to run this app. Vue.js调用API数据的表格添加搜索栏筛选功能失效问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js调用API数据的表格添加搜索栏筛选功能失效问题求助

问题定位
  • 当前表格组件仅支持接收原始数据源渲染,未实现搜索筛选逻辑,也没有预留搜索关键词的入参
  • 搜索输入框的事件监听结果没有正确传递到表格组件,导致表格无法感知搜索关键词变化
  • 渲染表格行时直接绑定原始data.rows,没有根据关键词做过滤后再渲染
修复方案

1. 改造表格组件

<template>
<table class="mt-12 border-2 border-gray-600">
  <thead>
    <tr>
      <th v-for="header in data.headers" :key="header" class="text-left border-l-2 border-gray-600 border-b-2 border-gray-600 bg-red-400 ">{{ header }}</th>
    </tr>
  </thead>
  <tbody>
    <!-- 遍历过滤后的行数据而非原始数据 -->
    <tr v-for="(rows, index) in filteredRows" :key="index">
      <td v-for="row in rows" :key="row" class="border-l-2 border-gray-600"  >{{ row }}</td>
    </tr>
  </tbody>
</table>
</template>
<script>
export default {
  props: {
    data: {
      type: Object,
      // 修正默认值写法,避免多组件实例共享引用
      default: () => ({ headers: [], rows: [] })
    },
    // 新增搜索关键词入参
    searchKeyword: {
      type: String,
      default: ''
    }
  },
  computed: {
    filteredRows() {
      const keyword = this.searchKeyword.trim().toLowerCase()
      // 关键词为空直接返回全量行
      if (!keyword) return this.data.rows
      // 匹配任意单元格包含关键词的行,不区分大小写
      return this.data.rows.filter(row => {
        return row.some(cell => String(cell).toLowerCase().includes(keyword))
      })
    }
  }
}
</script>
<style src="../assets/tailwind.css"/>

改动说明

  • 新增searchKeyword属性接收父组件传递的搜索内容
  • 新增计算属性filteredRows实现过滤逻辑,不会修改原始API返回的数据源
  • 表格行渲染绑定过滤后的结果,关键词为空时自动恢复全量数据展示

2. 父组件调用示例

如果搜索输入框放在表格组件的父级,按以下方式联动即可:

<template>
  <div class="p-4">
    <!-- 搜索输入框双向绑定搜索值 -->
    <input 
      type="text" 
      placeholder="输入内容搜索" 
      v-model="searchVal"
      class="border border-gray-500 p-2 rounded mb-4"
    />
    <!-- 传递原始数据和搜索关键词到表格组件 -->
    <TableComponent :data="tableData" :search-keyword="searchVal" />
  </div>
</template>
<script>
import TableComponent from './TableComponent.vue'
export default {
  components: { TableComponent },
  data() {
    return {
      searchVal: '',
      tableData: {
        headers: [],
        rows: []
      }
    }
  },
  mounted() {
    // 替换为你的API请求逻辑
    this.getApiData()
  },
  methods: {
    async getApiData() {
      const res = await fetch('你的API接口地址')
      const result = await res.json()
      // 原始数据完整存储,不要直接修改该变量用于筛选
      this.tableData = result
    }
  }
}
</script>

如果搜索框和表格跨多层组件,可通过vuex/pinia存储全局搜索关键词,避免逐层传递props

内容的提问来源于stack exchange,提问作者user14123102

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 03:27:05