✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Use v-if and v-for in the Same Vue Element

Aug 18, 2020 1 min read

I had this Vue component that iterated through a map and displayed a <div> for each element.

<div v-for="node in nodes" class="node"></div>

I needed to add a v-if statement inside this v-for loop so that it only rendered nodes with id > 3.

However, there’s an issue when we try to use v-if and v-for in the same element tag. We can’t and shouldn’t.

We can use <template> to generate the v-for loop. Template tags won’t be rendered to the browser but will still parse through its contents and render out the HTML.

We’ll also have to move all the attributes from the original <div v-for=""> to the <div v-if="">.

<template v-for="node in nodes">
    <div v-if="node.id > 3" class="node"></div>
</template>