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

Vue中表格实现搜索过滤功能无效果且无编译报错如何解决?

功能失效原因
  • 渲染列表时始终遍历原始的quotes全量数组,searchResults方法返回的过滤结果没有被接收和使用,页面自然不会跟随搜索操作更新
  • 直接使用match匹配搜索词存在两个问题:一是默认区分大小写,匹配精度不符合常规搜索预期;二是如果用户输入正则特殊字符会触发匹配异常,改用字符串includes方法更稳妥
  • 没有预留存储过滤结果的响应式变量,也没有处理清空搜索后恢复全量数据的逻辑
修复步骤
  1. 新增响应式变量filteredQuotes存储要渲染的列表数据,初始状态和接口返回时都和原始quotes保持同步
  2. 修改searchResults方法,把过滤后的结果赋值给filteredQuotes,搜索词为空时直接恢复全量数据
  3. 模板中列表遍历的数据源从quotes改为filteredQuotes
完整修改后代码

模板代码

<template>
  <div class="container">
    <h3>Quotes</h3>
    <div class="controllers">
      <div class="search">
         <input id="search-item" type="text" placeholder="Search for a quote..." v-model="searchText"/>
         <button @click="searchResults()" class="search-btn">Search</button>
      </div>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Source</th>
          <th scope="col">Context</th>
          <th scope="col">Quote</th>
          <th scope="col">Theme</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="quote in filteredQuotes" v-bind:key="quote.quote"> 
          <th scope="row">{{quote.context}}</th>
          <td>{{quote.source}}</td>
          <td>{{quote.quote}}</td>
          <td>{{quote.theme}}</td>
        </tr>
      </tbody>
    </table> 
  </div> 
</template>

脚本代码

import axios from 'axios';
export default {
  name: 'Quotes',
  data() {
    return {
      searchText: '',
      quotes: [],
      filteredQuotes: []
    };
  },
  mounted() {
    axios
      .get('https://gist.githubusercontent.com/benchprep/dffc3bffa9704626aa8832a3b4de5b27/raw/quotes.json')
      .then(res => {
        this.quotes = res.data;
        this.filteredQuotes = res.data;
      })
    },
  methods: {
    searchResults() {
      if (this.searchText.trim().length === 0) {
        this.filteredQuotes = this.quotes;
        return;
      }
      const searchKey = this.searchText.trim().toLowerCase();
      this.filteredQuotes = this.quotes.filter(quote => {
        // 如需扩展匹配来源、主题等字段,直接在下方添加或条件即可
        return quote.quote?.toLowerCase().includes(searchKey)
      });
   },
}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:27:03