Packy
Packy

Reputation: 3573

Vue-Lottie and Nuxt

Anyone get Vue-Lottie working with Nuxt? I tried to import it as Vue-Lotti said to:

import Lottie from './lottie.vue';

this says it cant find the package.

Then I tried how Nuxt had it:

import Lottie from 'vue-lottie';

this gives me an "Unexpected token <" error.

What am I missing?

Upvotes: 3

Views: 4515

Answers (5)

dudintv
dudintv

Reputation: 51

I found a working solution for Nuxt 3 and Composition API:

nuxt.config.ts:

export default defineNuxtConfig({
  plugins: [{ src: '~/plugins/lottie', mode: 'client' }],
})

plugins/lottie.js:

import lottie from 'lottie-web'
    
export default defineNuxtPlugin((nuxtApp) => nuxtApp.provide('lottie', lottie))

TheComponent.vue:

<script setup>
    const nuxtApp = useNuxtApp();

    onMounted(() => {    
        nuxtApp.$lottie.loadAnimation({ ... });

Upvotes: 3

zoix
zoix

Reputation: 141

If you want to use vue-lottie, you need to import the right lottie.vue component, located in your node_modules folder:

import Lottie from 'vue-lottie/src/lottie.vue'

Hope it works.

Upvotes: 6

Lamat
Lamat

Reputation: 31

I use lottie-web, simply install it with npm -> npm install lottie-web or yarn -> yarn add lottie-web

Then create a file in your plugin folder -> plugins/lottie.js and add this code:

import lottie from 'lottie-web';

export default ({ app }, inject) => {
  inject('lottie', lottie);
};

Finally register it in your nuxt.config.js :

plugins: [{ src: '~/plugins/lottie', mode: 'client' }],

Now you can use lottie anywhere in your nuxt application with this.$lottie.

See this code snipped to get you started:

<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: 'your_path/lottie.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>

Upvotes: 3

Marvin Parada
Marvin Parada

Reputation: 111

I use lottie-web instead of vue-lottie with my VueJS apps and I had a similar problem to yours.

The way I made it work was to install it normally with npm install lottie-web and then call it in my components as: import lottie from 'lottie-web/build/player/lottie';.

Perhaps you have to also type in the path in the same manner with vue-lottie.

Upvotes: 6

Lucas Silva
Lucas Silva

Reputation: 11

import lottie from 'lottie-web'

should work

Upvotes: 1

Related Questions