vue使用lottie-web

该文章介绍了如何在Vue3项目中封装lottie-web插件,包括安装、组件定义、属性配置以及事件处理。通过定义一个名为Lottie的组件,利用lottie-web库加载和控制动画,同时提供了autoplay、loop等属性来自定义动画行为。在组件使用时,可以绑定数据和事件,实现动画的播放和停止功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue3封装lottie插件

安装

npm install lottie-web -S

Lottie.vue


<template>
  <div ref="dom" class="lottie"></div>
</template>

<script lang="ts">
  import lottie from 'lottie-web';
  import { onMounted, ref, defineComponent } from 'vue';

  import type { LottieEvent } from './type';

  import { propTypes } from '/@/utils/propTypes';
  export default defineComponent({
    name: 'Lottie',
    props: {
      // renderer: propTypes.oneOf(['svg', 'canvas', 'html']).def('svg'),
      loop: propTypes.bool.def(true),
      autoplay: propTypes.bool.def(true),
      animationData: propTypes.any,
    },

    emits: ['getAnimation'],
    setup(props, { emit }) {
      // 创建 lottie接收变量 和 获取dom
      const animation = ref<LottieEvent>();
      const dom = ref<Element>();

      // 初始化渲染 lottie动画,并返回 lottie对象
      onMounted(() => {
        animation.value = lottie.loadAnimation({
          container: dom.value as Element, // 绑定dom节点
          renderer: 'svg', // 渲染方式:svg、canvas、html
          loop: props.loop, // 是否循环播放,默认:false
          autoplay: props.autoplay, // 是否自动播放, 默认true
          animationData: props.animationData, // AE动画使用bodymovie导出的json数据
        });

        emit('getAnimation', animation.value);
      });
      return {
        dom,
      };
    },
  });
</script>

<style scoped>
  .lottie {
    width: 200px;
    height: 200px;
  }
</style>

使用

 <Lottie
          class="like"
          :loop="true"
          :autoplay="false"
          :animation-data="micPhone"
          @get-animation="getAnimation"
          @click="startRecord"
        />

引入json

  import micPhone from '/@/assets/lottie/micPhone.json';
  import { Lottie } from '/@/components/Lottie';
  import type { LottieEvent } from '/@/components/Lottie/src/type';
   /**动画*/
      const animationLottie = ref<LottieEvent>();
      const getAnimation = (animation: LottieEvent) => {
        animationLottie.value = animation;
      };
      const animationFlag = ref(true);

      function startRecord() {
        if (animationFlag.value) {
          animationLottie.value!.play();
          
        } else {
          animationLottie.value!.stop();
         
        }
        animationFlag.value = !animationFlag.value;
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值