Using Lottie with Nuxt/Vue
Vue
Lottie
JavaScript
Nuxt
Implement beautiful animations in to your Nuxt application with a breeze, by exposing the Lottie-web API with these few steps.
Install lottie-web by running
npm install lottie-web
Register and add to config
Create a file inside your plugins folder called lottie.js
and add the following code.
plugins/lottie.js
import lottie from 'lottie-web';
// makes lottie api available from this.$lottie in a nuxt application
export default ({ app }, inject) => {
inject('lottie', lottie);
};
Then register the new plugin in your nuxt.config.js
file. Usually located in your root folder.
nuxt.config.js
plugins: [{ src: '~/plugins/lottie', mode: 'client' }],
Access lottie in all .vue files
Restart your app by quitting the process by pressing control
+ c
(ctrl
+ c
on windows) or just close the terminal window and run npm run dev
. Hey
Now that you have registered the new plugin and restarted the app, you can access lottie with this.$lottie
Animate.vue
<template>
<div
ref="animationElement"
class="animation"
/>
</template>
<script>
mounted() {
this.$lottie.loadAnimation({
container: this.$refs.animationElement, // the dom element that will contain the animation
loop: false,
autoplay: false,
path: '/animation/logo.json', // the path to the animation json
})
},
</script>
Bonus:
We can also quite easily add interactions to our animating design by using the lottie API
Animate.vue
<template>
<div
ref="animationElement"
class="animation"
@mouseover="open"
@focus="open"
@mouseleave="close"
@blur="close"
/>
</template>
<script>
export default {
mounted() {
this.$lottie.loadAnimation({
container: this.$refs.animationElement, // the dom element that will contain the animation
loop: false,
autoplay: false,
path: '/animation/logo.json', // the path to the animation json
})
},
methods: {
close() {
this.$lottie.setSpeed(1)
this.$lottie.setDirection(1)
this.$lottie.play()
},
open() {
this.$lottie.setSpeed(1.5)
this.$lottie.setDirection(-1)
this.$lottie.play()
},
},
}
</script>
Let's break down the code.
- We prevented the animation by setting
loop: false
when we created the file. - Autoplay was set to
false
leaving the logo static - We created 2 methods to start the animation
open()
andclose()
. Inside of the methods we tell the animation what we'd like it to do.open()
sets the animation speed to1
(original speed) direction to1
(forward) and then start the animation by runningplay()
close()
increases the animation speed (or decreases the duration) and sets the direction to-1
(backwards) and then start the animation by runningplay()
- We add these methods to the container element
$refs.animationElement
with the inline eventhandlers that the Vue API provides@mouseover="open"
Runs open when the mouse is over the element@focus="open"
Runs open if the element has focus e.g. for keyboard users@mouseleave="close"
Reverts the animation once the mouse leaves the element@blur="close"
Runs when the element looses the focus state.