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