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

Vue中如何在同一组件内循环含不同类型对象的数组并动态传参

Vue 循环渲染时按对象类型动态传Props实现方案

方案1:模板内直接条件判断(适合属性少的简单场景)

直接在props绑定时用三元表达式,不符合条件的属性传入undefined,Vue会自动忽略未定义的Props传入:

<div v-for="item in operations" :key="item.id">
  <my-component 
    :size="item.type === 'mise_en_prep' ? item.size : undefined"
    :tax="item.type === 'invoice' ? item.tax : undefined"
    :invoice="item.type === 'invoice' ? item.referenceInvoice : undefined"
  />
</div>

方案2:动态对象绑定(推荐,易维护扩展性强)

利用Vue支持v-bind直接绑定一个Props对象的特性,把判断逻辑封装到方法里,模板更简洁:

第一步:添加Props生成方法

在组件的methods里新增逻辑,根据传入的item返回对应Props对象:

methods: {
  getOperationProps(item) {
    switch(item.type) {
      case 'mise_en_prep':
        return { size: item.size }
      case 'invoice':
        return {
          tax: item.tax,
          invoice: item.referenceInvoice
        }
      default:
        return {}
    }
  }
}

第二步:模板绑定动态Props

用v-bind直接绑定方法返回的对象即可:

<div v-for="item in operations" :key="item.id">
  <my-component v-bind="getOperationProps(item)" />
</div>

该方案优势:后续新增type类型只需修改getOperationProps方法的分支逻辑,无需改动模板代码,属性多的场景下可读性更高。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:24:08