【Vue3组件】LottieAnimation组件封装,用于流畅的页面动画效果

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"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值