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

Vue项目中如何根据选中月份过滤多层嵌套数组内的商品列表

Vue多层嵌套分期数据的月份筛选实现方案

实现思路

  • 先定义3个核心响应式变量:原始商品列表、选中的月份值、过滤后的展示列表
  • 过滤逻辑需要遍历两层installment嵌套数组,判断当前商品是否存在符合选中月份的分期配置
  • 监听选中月份的变化,自动触发过滤逻辑更新展示列表
  • 默认保留active为true的有效商品

核心过滤逻辑说明

因为你的installment是两层数组嵌套,判断单个商品是否符合筛选条件的逻辑为:只要该商品的任意一层嵌套数组中存在months等于选中值的分期项,就保留该商品。

完整代码示例

模板部分

<template>
  <div>
    <!-- 月份选择器 -->
    <select v-model="selectedMonth" @change="filterProducts">
      <option :value="null">请选择分期月份</option>
      <option :value="6">6期</option>
      <option :value="12">12期</option>
      <option :value="18">18期</option>
    </select>

    <!-- 过滤后的商品列表 -->
    <div class="product-list">
      <div v-for="(product, idx) in filteredProducts" :key="idx">
        <p>{{ product.installment[0][0].product }}</p>
      </div>
    </div>
  </div>
</template>

脚本部分(Vue3组合式API示例)

<script setup>
import { ref, reactive } from 'vue'

// 原始商品数据
const originProducts = reactive([
  {
    "active": true,
    "installment": [
      [
        {
          "product": "Ipad",
          "months": 12,
          "installment": 63.94
        }
      ],
      [
        {
          "product": "Ipad",
          "months": 6,
          "installment": 63.94
        }
      ]
    ]
  },
  {
    "active": true,
    "installment": [
      [
        {
          "product": "Iphone",
          "months": 12,
          "installment": 63.94
        }
      ],
      [
        {
          "product": "Iphone",
          "months": 6,
          "installment": 63.94
        }
      ]
    ]
  },
  {
    "active": true,
    "installment": [
      [
        {
          "product": "Mac",
          "months": 18,
          "installment": 63.94
        }
      ],
      [
        {
          "product": "Mac",
          "months": 24,
          "installment": 63.94
        }
      ]
    ]
  }
])

// 选中的月份,默认未选择
const selectedMonth = ref(null)
// 过滤后的商品列表,默认展示全部有效商品
const filteredProducts = ref([...originProducts.filter(item => item.active)])

// 过滤方法
const filterProducts = () => {
  // 未选月份时返回全部有效商品
  if (!selectedMonth.value) {
    filteredProducts.value = originProducts.filter(item => item.active)
    return
  }
  // 按选中月份过滤
  filteredProducts.value = originProducts.filter(product => {
    if (!product.active) return false
    // 两层遍历判断是否存在匹配的分期月份
    return product.installment.some(subArr => {
      return subArr.some(installmentItem => installmentItem.months === selectedMonth.value)
    })
  })
}
</script>

兼容说明

如果使用Vue2选项式API,只需要把变量定义在data中,过滤方法放在methods里,可通过watch监听selectedMonth变化自动触发过滤即可。

内容的提问来源于stack exchange,提问作者JesúsDel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:54:05