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

Vue.js根据类型动态选择组件实现列表循环的方法

Fixing Duplicate Loops with Vue Dynamic Components

Your current code runs two separate v-for loops (one for <email-queue-item> and one for <queue-item>) and then uses v-if/v-else to filter them out, which is inefficient and redundant. Here's how you can fix this by using Vue's dynamic components to pick the right component before rendering each list item, all in a single loop:

Basic Solution (Global Type Check)

If your type variable applies to the entire queue (like in your original code), you can directly conditionally bind the is attribute to choose the component:

<component
  v-for="item in queue"
  :key="item.id"
  :is="type === 'EmailMessage' ? 'email-queue-item' : 'queue-item'"
  :item="item"
></component>

How This Works:

  • We only loop through queue once, eliminating the redundant iteration from your original code.
  • The :is directive dynamically selects which component to render based on your type condition.
  • All props (like :item) are passed to whichever component is rendered, just like with static components.

Scalable Solution (Per-Item Type Check)

If your queue might contain items of different types (not just a single global type), you can add a method to map item types to component names for better scalability:

Template Code:

<component
  v-for="item in queue"
  :key="item.id"
  :is="getComponentForItem(item.type)"
  :item="item"
></component>

Script Code:

export default {
  // ... other component options
  methods: {
    getComponentForItem(itemType) {
      switch(itemType) {
        case 'EmailMessage':
          return 'email-queue-item';
        // Add more cases here as you introduce new component types
        // case 'SmsMessage': return 'sms-queue-item';
        default:
          return 'queue-item'; // Fallback to the generic component
      }
    }
  }
}

Key Notes:

  • Make sure all components (email-queue-item, queue-item, etc.) are properly registered—either globally with Vue.component() or locally in your parent component's components option.
  • This approach keeps your template clean and makes it easy to add new component types later without cluttering your template with more v-if conditions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:34:33