Vue
<template>
<div
v-if="visible"
ref="animationRef"
:style="{...styles}"
:class="['lottie-animate', ...className]"
/>
</template>
<script>
import lottie from 'lottie-web';
export default {
props: {
className: {
type: Array,
default: () => []
},
visible: {
type: Boolean,
default: () => true,
},
styles: {
type: Object,
default: () => {}
},
animationData: {},
},
data() {
return {
animationInstances: null
}
},
methods: {
init() {
if (!this.animationData) return;
this.animationInstances = {};
if (typeof this.animationData === 'function') {
this.animationData().then(this.initAnimate);
} else {
this.initAnimate(this.animationData);
}
},
initAnimate(animationData) {
this.animationInstances = lottie.loadAnimation({
container: this.$refs.animationRef,
renderer: 'svg',
loop: true,
autoplay: true,
animationData,
});
this.$emit('on-init', this.animationInstances);
}
},
watch: {
visible() {
if (this.animationInstances || !this.visible) return;
this.init();
}
},
mounted() {
if (!this.visible) return;
this.init();
},
beforeDestroy() {
this.animationInstances?.destroy?.();
}
}
</script>
<style scoped>
</style>
<template>
<Animation :animationData="animationData" />
</template>
<script>
import Animation from "@/components/animation";
export default {
data() {
return {
animationData: () => import('@/assets/lottie/header/data.json')
}
},
components: {
Animation: Animation
}
}
</script>
React
import React, { useRef, useEffect } from 'react';
import lottie from 'lottie-web';
import classNames from 'classnames';
const Animation = ({ className, visible = true, style, animationData, onInit }) => {
const el = useRef();
const animationInstances = useRef();
function init() {
if (!animationData) return;
animationInstances.current = {};
if (typeof animationData === 'function') {
animationData().then(initAnimate);
} else {
initAnimate(animationData);
}
function initAnimate(animationData) {
animationInstances.current = lottie.loadAnimation({
container: el.current,
renderer: 'svg',
loop: true,
autoplay: true,
animationData,
});
onInit?.(animationInstances.current);
}
}
useEffect(() => {
if (!visible) return;
init();
return () => {
animationInstances.current?.destroy?.();
};
}, []);
useEffect(() => {
if (animationInstances.current || !visible) return;
init();
}, [visible]);
return (
<div
ref={el}
style={{ visibility: !visible && 'hidden', ...style }}
className={classNames('lottie-animate', className)}
></div>
);
};
export default Animation;
const animationData = () => import('@/assets/lottie/header/data.json');
const Header = () => {
return (
<Animation animationData={animationData} />
)
}