--- title: Use Key Attribute to Force Re-render Animations impact: MEDIUM impactDescription: Without key attributes, Vue reuses DOM elements and animation libraries like AutoAnimate cannot detect changes to animate type: gotcha tags: [vue3, animation, key, autoanimate, rerender, dom] --- # Use Key Attribute to Force Re-render Animations **Impact: MEDIUM** - Vue optimizes performance by reusing DOM elements when possible. However, this optimization can prevent animation libraries (like AutoAnimate) from detecting changes, because the element is updated in place rather than re-created. Adding a `:key` attribute forces Vue to treat changed elements as new, triggering proper animations. ## Task Checklist - [ ] Add `:key` to elements that should animate when their content changes - [ ] Use unique, changing values for keys (not indices) - [ ] For route transitions, add `:key="$route.fullPath"` to `` - [ ] Apply `v-auto-animate` to the parent element of keyed children **Problematic Code:** ```vue ``` **Correct Code:** ```vue ``` ## Why This Works When Vue sees a `:key` change: 1. It considers the old element and new element as different 2. The old element is removed (triggering leave animation) 3. A new element is created (triggering enter animation) Without `:key`: 1. Vue sees the same element type in the same position 2. It updates the element's properties in place 3. No DOM addition/removal occurs, so no animation triggers ## Common Use Cases ### Animating Text Content Changes ```vue ``` ### Animating Dynamic Components ```vue ``` ### Animating Route Transitions ```vue ``` ## With Vue's Built-in Transition The same principle applies to Vue's `` component: ```vue ``` ## Caution: Performance Implications Using `:key` forces full component re-creation. For frequently changing data: - The entire component tree under the keyed element is destroyed and recreated - Any component state is lost - Consider whether the animation is worth the performance cost ```vue ``` ## Reference - [Vue.js Animation Techniques](https://vuejs.org/guide/extras/animation.html) - [AutoAnimate with Vue](https://auto-animate.formkit.com/#usage-vue) - [Vue.js v-for with key](https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key)