DEV Community

İbrahim Turan
İbrahim Turan

Posted on

Effortless Animations With `AutoAnimate` in Vue 3

If you work in a startup you will know that you barely have time to implement something properly. Spending time on animation is mostly seen as unnecessary. Also, when you do something without animations on the frontend side, you will always feel like something is missing. As a frontend developer which works in a little startup, I always want to add some little animations as quickly as possible to indicate user when something changes. So, I started to search for options to achieve this because without animations website looks so much pale, like woodwork without polishing.

Recently, I found the AutoAnimate library that aims to animate things almost effortlessly. Also, they support all the major frontend frameworks right now which is awesome. It's like a gem for the tight-schedule startup workers. So, I implement AutoAnimate in all of our frontend projects in one day. I know still so many things are not perfect on the animation side but having little is always better than none. So, today I will share how to implement auto-animate to Vue 3 projects also I will explain some tricks I use for the edge cases.

In this article I will show examples and usage for Vue 3 but for the other frameworks, you can read documentation.

Creating Vue Project

I will use Vue 3, Vite, typescript, and tailwind to demonstrate how to add and use auto-animate. Vue is not necessary you can use it in all the mainstream frontend frameworks that auto-animate supports.

So, let's create and Vue 3 app with create-vue library created by the Vue team. These are my options to create the project.

**Project name:** … auto-animate-example
✔ **Add TypeScript?** … No /  Yes
✔ **Add JSX Support?** …  No  / Yes
✔ **Add Vue Router for Single Page Application development?** …  No  / Yes
✔ **Add Pinia for state management?** …  No  / Yes
✔ **Add Vitest for Unit Testing?** … No /  Yes
✔ **Add an End-to-End Testing Solution?** › No
✔ **Add ESLint for code quality?** … No /  Yes
✔ **Add Prettier for code formatting?** …  No  / Yes

Scaffolding project in .../projects/auto-animate-example...
Done. Now run:
**cd auto-animate-example**
**npm install**
**npm run dev**


Enter fullscreen mode Exit fullscreen mode

Before running it I will add tailwind and auto-animate.

Adding Tailwind

You can add Tailwind with the commands below. When you have done it successfully you will have tailwind.config.js and postcss.config.js files inside the project folder.



npm install -D tailwindcss
npx tailwindcss init


Enter fullscreen mode Exit fullscreen mode

The first thing l will do is update the tailwind.config.js file name to tailwind.config.cjs otherwise they won't work in the Vite project. You should do the same thing for postcss.config.js too. Then, update the tailwind.config.cjs file as shown below so tailwind will search your components to understand which classes are in use and which classes will be pruned.



/** @type {import('tailwindcss').Config} */  
module.exports = {  
  content: [  
  "./index.html",  
    "./src/**/*.{js,ts,jsx,tsx,vue}",  
  ],  
  theme: {  
  extend: {},  
  },  
  plugins: [],  
}


Enter fullscreen mode Exit fullscreen mode

The next thing I will do is remove the src/assets/base.css file and modify src/assets/main.css as shown below. That way I can access all the tailwind classes in the whole project. The main.css file imported main.ts by default so you don't have to import it.



@tailwind base;  
@tailwind components;  
@tailwind utilities;


Enter fullscreen mode Exit fullscreen mode

How AutoAnimate Works?

As you can read from the documentation when the listed conditions below happen, your elements going to be animated.

  • A child is added in the DOM.
  • A child is removed in the DOM.
  • A child is moved in the DOM.

Cool thing is, AutoAnimate read user preference about animations with the prefers-reduced-motion setting and disable animations automatically.

Adding AutoAnimate

Lastly, I will add auto-animate to the project after that, I can show you examples of animating things in the project.



npm install @formkit/auto-animate


Enter fullscreen mode Exit fullscreen mode

I will use auto-animate as a global directive so, I need to configure it that way. I always separate libraries that need configuration under the plugins folder to prevent spaghetti code in the main.ts file. Hence, I will create a file named src/plugins/auto-animate.ts to configure auto-animate.



// src/plugins/auto-animate.js file  
import { autoAnimatePlugin } from '@formkit/auto-animate/vue'  
import type { App } from 'vue';  

export default (app: App): App => {  
  return app.use(autoAnimatePlugin);  
};


Enter fullscreen mode Exit fullscreen mode


// main.ts file  
import { createApp } from 'vue'  
import App from './App.vue'  
import initAutoAnimate from '@/plugins/auto-animate';  
import './assets/main.css'  

const app = createApp(App);  

initAutoAnimate(app);  

app.mount('#app');


Enter fullscreen mode Exit fullscreen mode

We are ready to go. So I will run the project with npm run dev command.

I will not bother you with creating components etc. I will just show examples in dummy code if you need details you can see all the examples in the example project that I will share the end of the article.

Examples

Adding/Removing elements to DOM

When you add remove/add new elements dom, means that when you change visibility with v-if. You should add v-auto-animate directive to parent of element that will be animated. This parent element should be always visible otherwise your animation may not run correctly.



<collapse v-auto-animate>  
  <header @click="toggleBody">  
  Header  
  </header>  

 <body v-if="isBodyVisible">  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.  
    Donec posuere malesuada nulla, vitae congue metus rutrum ac.  
    Aliquam placerat metus consectetur nisi venenatis, eget tristique ligula consectetur.  
    Phasellus quis blandit nulla. Vestibulum tempus lectus elit, sit amet accumsan ligula  
    consectetur sit amet. Phasellus egestas, mi et dapibus pulvinar, ipsum augue vulputate  
    metus, vel suscipit nunc velit id tellus. Vestibulum viverra dolor non euismod malesuada.  
  </body>  
</collapse>


Enter fullscreen mode Exit fullscreen mode

example with no animation

example with animation
https://res.cloudinary.com/djsydl9fh/image/upload/v1677937200/Articles/f1646cf2-8a86-4063-b405-d9fb659bb8c4_ljzss7.gif

Adding/Removing Item From the List

If you want to animate adding/removing items to list event, you should add v-auto-animate directive to parent of the looped items. That way the library automatically understand changes and animate items when they added or deleted.



<section class="mt-10">
 <div v-auto-animate>  
      <template v-for="item in items" :key="item.title">  
          <item />  
      </template>  
  </div>  

 <div>  
  <button @click="addNew"> Add New </button>  
  <button @click="removeRandom"> Remove random </button>  
 </div>  
</section>


Enter fullscreen mode Exit fullscreen mode

adding/removing item without animation

adding removing item with animation

https://res.cloudinary.com/djsydl9fh/image/upload/v1677939127/Articles/bf3b6431-2768-454c-8e6c-fc736647ab77_xyaqei.gif

Change the Sorting of the List

I will use a randomizing function to change the order of list elements to avoid the complexity of changing elements one by one with a button. The animation will be same for both cases just this will little bit long for multi-index jumping.

change order without animations

change order with animation

https://res.cloudinary.com/djsydl9fh/image/upload/v1677949418/Articles/5f4cbfbd-1a22-4937-8551-bab0fe400c2b_ch6dci.gif

Change Duration of Animation

With directive, you can easily override the duration of animation by passing config object to the directive shown below.



<div v-auto-animate="{ duration: 100 }" class="flex flex-col gap-2">
      <template v-for="item in items" :key="item.title">
        <item /> 
      </template>
    </div>


Enter fullscreen mode Exit fullscreen mode

In this example, I override animation duration to 100 ms instead of default value(I don't know default value btw) with v-auto-animate="{ duration: 100 }" code.

Tricky Animations

I would like to list some edge cases I faced with. Most of them are related to html rendering, Vue updates html elements little as possible so adding key to the component forces them to re-render element completely that way they will animate while re-renderin occur.

  • Sometimes you would like to animate your components when their text changes or image source changes but it will not automatically be detected by auto-animations so you should add key to your HTML element and add v-auto-animate directive to the parent element of it. Then it will fade away with every key change.
  • If you would like to animate route change you should add unique key to your <router-view /> component like this <router-view :key="$route.fullPath">
  • Sometimes animation starts with under of other elements if that element doesn't have a background color(cause overlapping) or adds a scrollbar while the animation is running. If you want to prevent this, you should add overflow-hidden to the parent element. That way you don't see animations that occur outside of the element area.

More Examples

I just want to show you some basic things you can do with this library for other examples and use cases you can look at their documentation.

Creating Your Own Animation

Also, AutoAnimation library gives an API to create your own animation or extend/change the default animations it comes with. I won't cover that part in this article but you can read for more details in the documentation.

In conclusion, you can animate all your applications with AutoAnimate quickly and most importantly effortlessly. I shared all the details I know about AutoAnimate. I hope you enjoyed. You can see the example codes with the link below.

Top comments (1)

Collapse
 
muhammederdinc profile image
Muhammed Erdinç

This article is awesome. I enjoyed reading it.