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:
<code><!-- 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></code>Parent component:
<code><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 in</code>When 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]
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.