Skip to content

vue-v-if-with-v-for ​

v-if and v-for on the same element.

Why: it reads like "loop, and show the rows that pass", but in Vue 3 v-if runs first, before the loop. Its condition can't see the loop's item: v-if="!todo.done" reads a todo that doesn't exist yet, and the template fails at runtime. (Vue 2 did it the other way round, so code moved from Vue 2 changes meaning.) Guide: Vue.

vue
<script setup lang="ts">
type Todo = { readonly id: string; readonly title: string; readonly done: boolean };

const props = defineProps<{ todos: readonly Todo[] }>();
</script>

<template>
  <ul>
    <li v-for="todo in props.todos" v-if="!todo.done" :key="todo.id">{{ todo.title }}</li>
  </ul>
</template>

✅ Accepted: filter in a computed

✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { computed } from "vue";

type Todo = { readonly id: string; readonly title: string; readonly done: boolean };

const props = defineProps<{ todos: readonly Todo[] }>();
const open = computed(() => props.todos.filter((todo) => !todo.done));
</script>

<template>
  <ul>
    <li v-for="todo in open" :key="todo.id">{{ todo.title }}</li>
  </ul>
</template>

When the condition doesn't depend on the item (show the list only when it is open), put it on a wrapping element instead, or the loop on a <template v-for> around the element with v-if.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra