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:
Code Implementation Example
<!-- ❌ 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>Never use v-if and v-for on the same tag. Always filter data with a computed property first.