Effortless Animations With `AutoAnimate` in Vue 3
Tags: vite, vue, tailwindcss
Published: 2023-03-04 19:46:03


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](https://auto-animate.formkit.com/#usage-react).

## 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](https://github.com/vuejs/create-vue)** library created by the Vue team. These are my options to create the project.

```bash
✔ **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**
```
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
```

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.

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

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.

```css
@tailwind base;  
@tailwind components;  
@tailwind utilities;
```

## How `AutoAnimate` Works?
As you can read from the [documentation](https://auto-animate.formkit.com/#usage) 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.

```bash
npm install @formkit/auto-animate
```
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`.

```ts
// 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);  
};
```
```ts
// 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');
```
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.
```html
<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>
```
![example with no animation](https://res.cloudinary.com/djsydl9fh/image/upload/v1677937199/Articles/f45ade35-28cc-437a-aacd-dae6477de39a_lmuyho.gif)

![example with animation](https://res.cloudinary.com/djsydl9fh/image/upload/v1677937200/Articles/f1646cf2-8a86-4063-b405-d9fb659bb8c4_ljzss7.gif)
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.

```html
<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>
```
![adding/removing item without animation](https://res.cloudinary.com/djsydl9fh/image/upload/v1677939821/Articles/37ce0f29-e5db-4251-9621-fb40d82d8efd_xtdowt.gif)

![adding removing item with animation](https://res.cloudinary.com/djsydl9fh/image/upload/v1677939127/Articles/bf3b6431-2768-454c-8e6c-fc736647ab77_xyaqei.gif)

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](https://res.cloudinary.com/djsydl9fh/image/upload/v1677949413/Articles/d72ca1ee-cafc-4f12-aab8-50a03126ffac_siwhzg.gif)

![change order with animation](https://res.cloudinary.com/djsydl9fh/image/upload/v1677949418/Articles/5f4cbfbd-1a22-4937-8551-bab0fe400c2b_ch6dci.gif)

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.

```html
<div v-auto-animate="{ duration: 100 }" class="flex flex-col gap-2">
      <template v-for="item in items" :key="item.title">
        <item /> 
      </template>
    </div>
```
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](https://auto-animate.formkit.com/#examples).

## 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](https://auto-animate.formkit.com/#plugins).

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.

- [AutoAnimate documentation](https://auto-animate.formkit.com/)
- [Example code repo](https://github.com/turanibrahim/auto-animate-example)