Vue.js v-for key order affects transition animation and how to fix it
This article explains why using a numeric index as the key in a Vue.js v‑for loop can cause transition animations to apply only to the last element, and shows how switching the key to a unique string restores smooth, sequential animations.
The author encountered an issue where the transition animation of a Vue.js component only applied to the last item when removing elements generated by a v-for loop, because the key was set to a numeric index.
Child component:
<!-- Notice:-->
<transition :name="transitionName" @enter="enter" @leave="leave">
...... ..
</transition>
<!-- JS: -->
<script>
export default {
methods: {
enter(e) {
e.style.height = e.scrollHeight + "px";
},
leave(e) {
e.style.height = 0;
},
},
};
</script>
<!-- CSS: -->
<style>
transition: all 0.2s ease-in-out;
</style>Parent component:
<notice v-for="(item, index) in notices" :key="index">
......
</notice>
// JS:
data() {
return {
notices: []
};
},
// When a new notice is added, a timer is set to remove it
setTimeout(() => {
let index = 0; // assume we have obtained the index to remove, may not be sequential
this.notices.splice(index, 1);
}, time); // <code>time</code> is a random value passed inWhen the key value is a Number, each change to the notices array causes the DOM to re‑render, so the transition is only applied to the last element. If the key is a String, Vue uses a "in‑place reuse" strategy, allowing each element to animate smoothly.
Therefore, changing the key to a unique string (or any non‑repeating value) makes the animation work as expected, matching the behavior shown in the official Vue.js example.
In practice, the key should be a random, non‑repeating string or number rather than the default index, to avoid DOM reuse issues and ensure proper transition effects.
[End of article]
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
