Using Lottie files with Nuxt 2

Many times using animations on our website is not an easy job, so in this blog we are going to learn how to use Lottie animations within our project with nuxt.js easily.

What is a Lottie?

A Lottie is a JSON file containing vector settings of our animations, this format allows us to maintain a high quality and performance encoded animation, showing fidelity and compatibility between different devices, see the official guide.

View Lottie file example ->

Installing the lottie-web package

We are going to use the lottie-web package which is provided and sponsored by airbnb.io, to configure it you just need to add the dependency with yarn or npm.

yarn add lottie-web

Using the package

First of all, we are going to import the package into our component.

import lottie from 'lottie-web';

Now we have the lottie reference which can be used anywhere in the code, for that we are going to create a method that will allow us to generate an instance of our animation:

loadLottie(reference, file) {
  // Lottie config instance
  const animation = lottie.loadAnimation({
    container: this.$refs[reference],
    renderer: 'svg',
    loop: true,
    autoplay: true,
    path: `${window.location.origin}/animations/${file}.json`,
  });

  // Init animation
  animation.play();
}

Let's review some important points:

  • container: Dom element on which to render the animation.
  • renderer: svg / canvas / html to set the renderer.
  • loop: true / false / number.
  • autoplay: true / false it will start playing as soon as it is ready.
  • path: The relative path to the animation object. (animationData and path are mutually exclusive).

See more information about the api.

Note: path receives the relative path of your animation, so all your animations must be inside the static folder, for example: static/animations/{file-name}.json

Our loadLottie(...) method receives 2 parameters:

  • The first parameter is an HTML element that will serve as a container for our animation:
<div ref="animation-container"></div>
  • The second parameter is the name of the file without the .json extension.

To use the animation we are going to use the mounted hook. This will run our animation once the page loads.

mounted() {
  this.loadLottie('animation-container', 'animation-1');
}

That's it! Now we will have as a result a beautiful animation playing on our site:

Animation events

From here on out the only limitation is your imagination. You can create different configurations and customizations thanks to the extensive configuration api provided by the lottie-web package, and even make use of the different events as onComplete, onLoopComplete, onEnterFrame, onSegmentStart, for example:

animation.addEventListener('loopComplete', () => {
  console.log('Execute function...');
});

This is just a small usage reference. Explore your imagination and feel free to send me your amazing projects using this beautiful library.