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

Vue.js复选框过滤数组实现(不使用计算属性)

Vue.js 复选框过滤数组实现方案

问题修正要点

原代码存在v-model绑定变量未声明、重复定义methods、重复引入Vue库、复选框ID冲突以及未实现过滤逻辑等问题,以下是修正后的完整实现:

完整代码

JavaScript 部分

new Vue({
  el: "#app",
  data: {
    checkedNames: [], // 声明复选框绑定的数组
    todos: [
      { "Name": "CHS_200_TL_L62_TRUCK" },
      { "Name": "VHS_600_TL_L62_TRUCK" },
      { "Name": "VHS_116_TL_L62_TRUCK" },
      { "Name": "VHS_146_TX_L62_VAN" },
      { "Name": "VHS_613_TL_L62_TRUCK" },
      { "Name": "JE_50_OL_T62_TRUCK" },
      { "Name": "VHS_T10_OL_L62_TRUCK" },
      { "Name": "JE_59_OL_T62_TRUCK" },
      { "Name": "LEE_100_TL_L62_TRUCK" }
    ]
  },
  methods: {
    filterItems(todo) {
      // 未选中任何复选框时显示全部
      if (this.checkedNames.length === 0) return true;
      // 统一转大写避免大小写匹配问题
      const nameUpper = todo.Name.toUpperCase();
      // 检查是否包含任意选中的关键词
      return this.checkedNames.some(keyword => {
        return nameUpper.includes(keyword.toUpperCase());
      });
    }
  }
})

HTML 部分

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <input type="checkbox" id="vehicle1" name="vehicle" value="Truck" v-model="checkedNames"> 
  <label for="vehicle1">Truck</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle" value="Van" v-model="checkedNames"> 
  <label for="vehicle2">Van</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle" value="TX" v-model="checkedNames">
  <label for="vehicle3">TX</label><br>
  
  <!-- 调用方法实现过滤,无需computed属性 -->
  <li v-for="todo in todos.filter(filterItems)">
    {{ todo.Name }}
  </li>
</div>

核心逻辑说明

  1. v-model 绑定:checkedNames数组会自动同步选中的复选框值,无需手动处理
  2. 过滤规则:
    • 无选中项时显示所有条目
    • 统一转换为大写进行匹配,避免大小写敏感问题
    • 使用Array.some()判断条目名称是否包含任意选中的关键词
  3. 模板写法:直接在v-for中调用数组filter方法并传入过滤函数,完全不需要使用computed属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:45:31