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

Vue项目添加日期筛选规则时下拉选项移除后原有值丢失问题

解决Vue日期筛选器添加规则后原有行filterType消失的问题

问题根源

你当前的代码直接修改了全局的dateOptions数组,把已选中的filterType过滤掉。这会导致所有筛选行的下拉菜单都只能看到剩余未被选中的选项,而原有行已选中的filterType因为不在dateOptions里了,select控件找不到对应的<option>,绑定的filterType值就会丢失,所以显示消失。

解决方案

核心思路是保留原始的选项列表,不要修改它,而是为每一行单独计算可用的选项(排除其他行已选中的filterType,保留当前行自己的选中项)。

1. 调整数据定义,保存原始选项

修改data,新增originalDateOptions存储所有原始选项,避免后续修改它:

data() {
  return {
    dateFilters: [
      {
        dateType: "startDate",
        filterType: "eq",
        date: "",
      },
    ],
    // 存储所有原始筛选类型选项,固定不变
    originalDateOptions: [
      {value: "eq", label: "Date is"},
      {value: "not", label: "Date is not"},
      {value: "lte", label: "Date is before"},
      {value: "gte", label: "Date is after"},
    ],
  };
}

2. 添加方法计算每行可用的选项

新增一个方法,根据当前行的索引,计算出这一行能选择的选项(排除其他行已选的,保留自己当前的选中项):

methods: {
  getAvailableOptions(currentIndex) {
    // 收集其他行已经选中的filterType
    const selectedTypes = this.dateFilters
      .filter((_, idx) => idx !== currentIndex)
      .map(filter => filter.filterType);
    
    // 从原始选项中筛选:排除其他行已选的,保留当前行自己的选中项
    return this.originalDateOptions.filter(option => {
      const currentFilter = this.dateFilters[currentIndex];
      return !selectedTypes.includes(option.value) || option.value === currentFilter.filterType;
    });
  },
  // 其他原有方法...
}

3. 修改模板,使用计算后的可用选项

把模板中筛选类型的下拉列表,从直接遍历dateOptions改为调用getAvailableOptions方法:

<select v-model="filter.filterType" class="form-select mr-1">
  <option
    v-for="option in getAvailableOptions(index)"
    :value="option.value"
    :key="option.value"
  >
    {{ option.label }}
  </option>
</select>

4. 调整添加规则的方法

不再修改选项数组,而是从原始选项中找出未被选中的选项来添加新行:

addDateFilter() {
  // 收集所有已选中的filterType
  const selectedValues = this.dateFilters.map(filter => filter.filterType);
  // 找出未被使用的选项
  const availableOptions = this.originalDateOptions.filter(option => !selectedValues.includes(option.value));
  
  if (availableOptions.length > 0) {
    this.dateFilters.push({
      dateType: "startDate",
      filterType: availableOptions[0].value,
      date: "",
    });
  }
}

5. 优化删除规则的方法(可选)

删除规则后,被删除的filterType会自动重新出现在其他行的下拉列表中,因为getAvailableOptions会实时计算,所以只需要保持原有删除逻辑即可:

clearDateFilterRule(index) {
  this.dateFilters.splice(index, 1);
}

效果说明

  • 添加新行时,已被其他行选中的filterType不会出现在新行的下拉菜单中;
  • 原有行的选中值不会消失,因为它们的下拉菜单会保留自己当前的选中项;
  • 删除某行后,该行使用的filterType会重新回到其他行的下拉选项中。

内容的提问来源于stack exchange,提问作者Yellow rain coat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:06:05