vue使用lottie动画

590 阅读1分钟

1、安装lottie-web。执行命令npm install lottie-web

2、封装lottie通用组件。

<template>
  <div
    ref="animation"
    :style="{ width, height }"
    @mouseover="mouseover"
    @mouseout="mouseout"
  ></div>
</template>

<script>

import { defineComponent, ref, onMounted } from 'vue'
import lottie from 'lottie-web'
export default defineComponent({
  name: 'Lottie',
  props: {
    width: {
      type: String,
      default: '100px',
    },
    height: {
      type: String,
      default: '100px',
    },
    src: {
      type: String,
      default: "https://assets10.lottiefiles.com/packages/lf20_dyiqnus5.json",
    },
    /**传入文件名称 */
    jsonData: {
      type: Object,
      default: () => null,
    },
    autoplay: {
      type: Boolean,
      default: false,
    },
    loop: {
      type: Boolean,
      default: true,
    },
  },
  setup (props) {
    let animation = ref(null)
    onMounted(() => {
      console.log((`../../iconJson/json/${props.jsonData}.json`))
      if (animation.value) {
        lottie.loadAnimation({
          container: animation.value,
          renderer: "svg",
          loop: props.loop,
          autoplay: props.autoplay,
          path: props.src,
          // animationData只能加载本地json,优先级高于path
          //animationData: props.jsonData,
          //拼接导入地址,使用时只需要传入目录下文件名,避免在不同的使用地方都需要引入
          animationData: require(`@/iconJson/json/${props.jsonData}.json`)

        })
      }
    });
    /**鼠标移上去播放*/
    function mouseover () {
      lottie.play()
    };
     /**鼠标移除停止*/
    function mouseout () {
      lottie.pause()
    };
    return {
      animation,
      mouseover,
      mouseout
    }
  }
})


</script>

3、新建iconJson文件夹,把lottie动画Json文件放在此文件夹下的Json目录下。目录下新建Index.js文件,注册封装的vue组件.

import Lottie from '@/components/lottie' // lottie组件

const req = require.context('./json', false, /.json$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

export default {
    install: (app) => {
        app.component("Lottie", Lottie)
    }
}

4、在main.js文件中引入并全局使用

import Lottie from '@/iconJson';
app.use(Lottie)

5、在需要使用的vue组件中使用。

<!--其中jsonData需要传入IconJson目录下的lottieFile的json文件的文件名称-->
<Lottie jsonData="test"></Lottie>