Frontend Development 4 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Vue.js v-for key order affects transition animation and how to fix it

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>&lt;!-- Notice:--&gt;
&lt;transition :name="transitionName" @enter="enter" @leave="leave"&gt;
  ...... ..
&lt;/transition&gt;

&lt;!-- JS: --&gt;
&lt;script&gt;
  export default {
    methods: {
      enter(e) {
        e.style.height = e.scrollHeight + "px";
      },
      leave(e) {
        e.style.height = 0;
      },
    },
  };
&lt;/script&gt;

&lt;!-- CSS: --&gt;
&lt;style&gt;
  transition: all 0.2s ease-in-out;
&lt;/style&gt;</code>

Parent component:

<code>&lt;notice v-for="(item, index) in notices" :key="index"&gt;
  ......
&lt;/notice&gt;

// 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]

frontendanimationVue.jskeytransitionv-for
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.