Skip to content

Instantly share code, notes, and snippets.

@horlarme
Created July 31, 2023 12:37
Show Gist options
  • Save horlarme/2dba8b628c543f7941fc8914c4f398dd to your computer and use it in GitHub Desktop.
Save horlarme/2dba8b628c543f7941fc8914c4f398dd to your computer and use it in GitHub Desktop.
Using LottieFiles (LottiePlayer) as a directive with Vue3

This gist takes you through the process of using lottie-player as a directive in Vue3 application.

Installing Lottie

Nuxt3 (using cdn)

Add the below object to the script list at app.head.script inside your nuxt.config file (nuxt.config.ts or nuxt.config.js, whichever applies to your case). */

{ src: 'https://unpkg.com/@lottiefiles/[email protected]/dist/lottie-player.js' }

PS: Because I make use of typescript, I also locally installed the package in other to use the typing. This might not apply to you case but if needed, you can install using

pnpm add @lottiefiles/lottie-player

Your config file should now look something like what's showing below.

export default defineNuxtConfig({
  ...restOfConfig,
  app:{
    head: {
      script:[{ src: 'https://unpkg.com/@lottiefiles/[email protected]/dist/lottie-player.js' }]
    }
  }
})

Creating Directive

Create a new plugin file and choose a name for it, in my case, it was named lottie-player or use the below command to quckly and easily create the plugin

pnpm nuxi add plugin lottie-player

Add the below code to the created plugin (lottie-player)

import { LottiePlayer } from '@lottiefiles/lottie-player'

export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.vueApp.directive('lottie-player', (el: HTMLElement, binding) => {
    const player = document.createElement('lottie-player') as LottiePlayer
    player.autoplay = binding.value?.autoplay || true
    player.loop = binding.value?.loop || true
    player.src = binding.value?.src || binding.value
    el.replaceChildren(player)
  })
})

Use this if not using typescript

export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.vueApp.directive('lottie-player', (el, binding) => {
    const player = document.createElement('lottie-player')
    player.autoplay = binding.value?.autoplay || true
    player.loop = binding.value?.loop || true
    player.src = binding.value?.src || binding.value
    el.replaceChildren(player)
  })
})

Usage

Example 1

<template>
<div class="w-1/2 aspect-video" v-lottie-player="'https://lottie.host/42bea3c1-eaec-453d-986f-404466e55652/eWLFzK0Q00.json'" />
</template>

Example 2

<template>
<div class="w-1/2 aspect-video" v-lottie-player="{ src: 'https://lottie.host/42bea3c1-eaec-453d-986f-404466e55652/eWLFzK0Q00.json', loop: false }" />
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment