lottie是什么就不多介绍了,自己封装了一个平时用的比较多的组件,主要用于快速使用lottie动画,支持自动播放
,循环播放
,暂停继续
必要的库–lottie-web
<template>
<div class="lottie" ref="lottieContainer"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch,withDefaults } from 'vue';
import lottie from 'lottie-web';
interface Props {
animationPath: string;
loop?: boolean;
autoplay?: boolean;
isPlaying?: boolean;
}
const props = withDefaults(defineProps<Props>(),{
loop: true,
autoplay: true,
isPlaying: true,
})
const lottieContainer = ref<HTMLDivElement | null>(null);
// @ts-ignore
const lottieInstance = ref<lottie.AnimationItem | null>(null);
onMounted(() => {
if (lottieContainer.value) {
fetch(props.animationPath)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(animationData => {
lottieInstance.value = lottie.loadAnimation({
container: lottieContainer.value as Element,
renderer: 'svg',
loop: props.loop ?? true,
autoplay: props.autoplay ?? true,
animationData: animationData,
});
})
.catch(error => {
console.error('Error loading Lottie animation:', error);
});
}
});
watch(
() => props.isPlaying,
(newVal) => {
if (lottieInstance.value) {
if (newVal) {
lottieInstance.value.play();
} else {
lottieInstance.value.pause();
}
}
}
);
</script>
使用时只需要传入animationPath
即可
例如
<LottieAnimation :animationPath="lottieList[getRandomInt()]" />
自动播放
,循环播放
,暂停继续
等
<LottieAnimation :animationPath="lottieList[getRandomInt()]" :loop="true" :autoplay="true" :isPlaying="true"/>