While writing a vue3 single file component i came across this issue. I am rendering this custom component inside a for loo. What is happening is any changes to the component template(tailwind class, changes to dom elements etc.) did not update all instances of this component – only the last OR the first instance was updating. Here is the code:
//File: CustomVenue.vue
<template>
<div class="flex items-center">
<img src="https://fastly.picsum.photos/id/1067/200/300.jpg?hmac=9UpH9GvB6swkUWpIG1N53lIk9vdO4YcIwlH59M8er18"
alt="" width="100" height="100"
>
<span class="ml-6 text-blue-700 font-semibold text-sm">Venue name</span>
</div>
</template>
<script setup>
const props = defineProps({
id: String
});
</script>
And this is how it is rendered inside the for loop:
<div class="flex flex-col gap-y-2">
<template v-for="(venue, index) in filteredVenues" :key="`custom_venue_${index}`">
<CustomVenue :id="`custom_venue_${index}`" />
</template>
</div>
It is a very simple component at this stage.
What i noticed is if i change the component definition to this:
<span class="ml-6 text-blue-700 font-semibold text-sm">Venue names - {{ id }}</span>
Basically just outputting the id propperty, things seem ok. All class changes in the template deifition affects all the rendered instance of this component.
Is this a bug? If not can someone please explain why the later version works? As you can see i even added the :key
arritube on the rendered instances as suggested while loop rendering.
The DOM in CustomVenue.vue has not changed. When Vue3’s Diff algorithm compares the old and new virtual DOM trees, it finds no difference and does not perform an update, which helps improve performance.
1