vite+vue3项目中使用 lottie 动画,如何在 template 中直接使用本地 json 文件路径

发布时间 2023-06-19 14:16:44作者: 蓓蕾心晴

安装 lottie-web

yarn add lottie-web 

封装  lottie 组件

<template>
  <div ref="animation" :style="{ width, height }"></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: "",
    },
    jsonData: {
      type: Object,
      default: () => null,
    },
    autoplay: {
      type: Boolean,
      default: true,
    },
    loop: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    let animation = ref(null)

    onMounted(() => {
      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,
        })
      }
    });

    return {
      animation
    }
  }
})


</script>

<style scoped></style>

全局注册 Lottie 组件

在 main.js 中

import Lottie from "./components/Lottie.vue";


const app = createApp(App) 
app.component("Lottie", Lottie)

在页面中使用(以下在  App.vue )

如果引入的是在线 cdn json 文件,可以直接使用 src,如果使用本地的 json 文件,可以使用 jsonData

<template>
    <div>
           <Lottie width="400px" height="400px" src="https://assets9.lottiefiles.com/packages/lf20_suhe7qtm.json" />
           <Lottie width="400px" height="400px" :jsonData="btn"></Lottie>
</div>
</template>

如果要在 src 中使用本地 json 文件,在 vite 项目中可以通过 import 动态导入 json 文件,并给 json url 路径后面加 "?url",否则会报警告:

runtime-core.esm-bundler.js:6873 [Vue warn]: Invalid prop: type check failed for prop "src". Expected String with value "[object Object]", got Object  
  at <Lottie width="400px" height="400px" src= {v: '5.6.9', fr: 25, ip: 0, op: 50, w: 1000, …} > 
  at <App>
<script setup>
import btn from "./assets/btn.json?url"
</script>

参考文章

参考 vite 官方文档

lottie官方文档

lottie动画资源文档