QA
Beginner LevelVue JS

Why is :key required in v-for loops and why should you never use v-if on the same element as v-for?

❓ Interview Prompt: Explain Vue Virtual DOM diffing with :key, and why placing v-if on the same element as v-for is an antipattern.

Why ':key' is Mandatory:

Like React, Vue uses a Virtual DOM diffing algorithm. When updating a list rendered with 'v-for', Vue uses the ':key' attribute as a unique identifier to track DOM nodes. Without unique keys (like database IDs), Vue defaults to an "in-place patch" strategy, which can corrupt form inputs and component state when list items are reordered or deleted.

Why 'v-if' + 'v-for' on the Same Element is Dangerous:

In Vue 3, 'v-if' has a higher priority than 'v-for' when placed on the same tag. This means the 'v-if' condition evaluates before the loop runs, so it cannot access loop variables like 'item' or 'index'!

The Correct Solution:

1
Filter the array using a computed property before looping over it, OR
2
Wrap the loop in a '<template v-for>' tag and put 'v-if' on the child element.

Code Implementation Example

html
<!-- ❌ CRITICAL BUG in Vue 3: v-if runs BEFORE v-for! -->
<!-- ReferenceError: todo is not defined -->
<!-- <li v-for="todo in todos" v-if="todo.isCompleted" :key="todo.id"> -->

<!-- ✅ SOLUTION 1: Filter via Computed Property (Best for performance) -->
<script setup>
import { ref, computed } from 'vue';
const todos = ref([{ id: 1, title: 'Task 1', isCompleted: true }]);
const completedTodos = computed(() => todos.value.filter(t => t.isCompleted));
</script>
<template>
  <ul>
    <li v-for="todo in completedTodos" :key="todo.id">{{ todo.title }}</li>
  </ul>
</template>
💡Vue 3 v-if priority over v-for and computed property filtering solution.
🎯 Interview Key Takeaway

Never use v-if and v-for on the same tag. Always filter data with a computed property first.

#v-for#v-if#Directives#Beginner
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?