Search code examples
vuejs2vue-componentv-for

Vuejs v-for add tag attribute or event listener depending on some condition


I have an array of objects on which I loop over in my template.

<div v-for="(list, idx) in collection" :key="list.id">
    <misc v-if="!idx" :is-master="!idx" :selection="list" v-on:report="onSelectionReport"></misc>
    <misc v-else :is-master="!idx" :selection="list"></misc>
</div>

As you can see, there are two "misc" tags. The only reason for this is that I only want the "report" event to bubble up from a single instance.

This works, though is there a way to save a v-if/v-else construct in a such case? (which would result in a single misc tag here).

Thank you.


Solution

  • You could define an inline event handler to check the value of idx:

    <div v-for="(list, idx) in collection" :key="list.id">
        <misc :is-master="!idx" :selection="list" v-on:report="arg => idx || onSelectionReport(arg)"></misc>
    </div>
    

    However, as @Lawrence Cherone suggested, it might be cleaner to do this logic inside the component - especially since you're passing idx as a property (via is-master) anyways.