Consider a Vue component rendering a list of items without using key attributes. What is the most likely behavior when the list changes?
<template>
<ul>
<li v-for="item in items">{{ item.text }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([{ id: 1, text: 'A' }, { id: 2, text: 'B' }])
</script>Think about how Vue tracks elements in a list to update efficiently.
Without keys, Vue cannot reliably track which items changed, so it may reuse DOM elements incorrectly, leading to UI glitches.
Given a Vue component rendering a list with duplicate keys, what will be the output after updating the list?
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">{{ item.text }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, text: 'First' },
{ id: 1, text: 'Duplicate' }
])
</script>Keys must be unique to help Vue track elements properly.
Vue requires keys to be unique. Duplicate keys cause Vue to overwrite or ignore elements, so only one item renders.
Identify the correct syntax for using the key attribute in a Vue 3 v-for loop.
<template>
<ul>
<li v-for="item in items" ???>{{ item.name }}</li>
</ul>
</template>Remember how to bind dynamic attributes in Vue templates.
The correct way to bind the key attribute dynamically is :key="item.id". Using key="item.id" treats it as a string literal. v-key is invalid. v-bind:key is valid but verbose; :key is shorthand.
Examine the code below. After removing the first item from items, the UI does not update as expected. What is the cause?
<template>
<ul>
<li v-for="item in items" :key="item.index">{{ item.text }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([
{ index: 0, text: 'One' },
{ index: 1, text: 'Two' },
{ index: 2, text: 'Three' }
])
function removeFirst() {
items.value.shift()
}
</script>Think about what happens when keys are based on array positions and the array changes.
Using the array index as key is problematic because when items are removed or reordered, keys do not uniquely identify the same item, causing Vue to reuse DOM nodes incorrectly.
Explain why Vue requires a unique key attribute on elements rendered with v-for. What role does it play in Vue's virtual DOM update process?
Think about how Vue compares old and new virtual DOM trees.
Vue uses keys to track elements between renders. This lets Vue detect changes precisely and update only what is necessary, improving performance and avoiding UI glitches.