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

Vue Bootstrap中for循环生成的多列搜索过滤器输入后条目消失如何解决

问题原因

  1. 字段名不匹配:fields配置中第一列的key写的是options,但实际数据源和filters中对应的字段名是option,拼写不一致导致第一列过滤绑定失效。
  2. 过滤逻辑写反:当前判断逻辑是「用户输入的内容包含表格字段值」,和需求的「表格字段值包含用户输入的内容」完全相反,所以输入任何内容都匹配不到结果。
  3. 过滤字段不完整:filters中只初始化了3个字段,剩下的type、class列的输入框绑定的属性不存在,Vue2中直接新增属性不会触发响应式更新,对应列过滤会失效。
  4. 分页总条数错误:当前rows计算属性返回的是原始数据总条数,过滤后分页的总条数应该取过滤后的数据长度,否则分页显示异常。

修正后的核心代码

import axios from "axios";

export default {
  data() {
    return {
      filters: {
        option: "",
        style: "",
        stock: "",
        type: "",
        class: "",
      },
      items: [],
      fields: [
        // 修正第一列key的拼写
        { key: "option", label: "Options", sortable: true },
        { key: "style", label: "Style", sortable: true },
        { key: "stock", label: "Stock", sortable: true },
        { key: "type", label: "Type", sortable: true },
        { key: "class", label: "Class.", sortable: true },
      ],
      perPage: 15,
      currentPage: 1,
    };
  },
  created() {
    this.getTable();
  },
  methods: {
    getTable() {
      axios
        .get("./data/options.json")
        .then((res) => (this.items = res.data))
        .catch((error) => console.log(error));
    },
  },
  computed: {
    rows() {
      // 改用过滤后的数据长度作为分页总条数
      return this.filteredItems.length;
    },
    filteredItems() {
      return this.items.filter((d) => {
        return Object.keys(this.filters).every((f) => {
          const filterVal = this.filters[f].trim().toLowerCase();
          // 修正过滤逻辑,增加大小写不敏感适配
          return filterVal.length < 1 || d[f].toString().toLowerCase().includes(filterVal);
        });
      });
    },
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:36:02