Lottie 是 Airbnb 开发的,一个适用于 Android、iOS、Web 和 Windows 的库,能够渲染 Adobe After Effects 动画特效。
yarn add lottie-web
MyLottie.vue
<template>
<div class="lottie">div>
template>
<script>
import lottie from 'lottie-web'
export default {
props: {
animationData: {
type: Object,
required: true
},
autoplay: {
type: Boolean,
default: true
},
loop: {
type: Boolean,
default: true
}
},
data () {
return {
lottie: null
}
},
mounted () {
this.intLottie()
},
methods: {
intLottie () {
const { animationData, autoplay, loop } = this
this.lottie = lottie.loadAnimation({
container: this.$el, // 渲染容器
renderer: 'svg', // 渲染方式 svg|canvas|html
loop, // 是否循环 true|false|number
autoplay, // 自动播放 true|false
animationData // lottie json文件
})
}
}
}
script>
<style lang="scss" scoped>
.lottie {
width: 200px;
height: 200px;
}
style>
在页面引用组件,可以去官方社区下载动画json
<template>
<div>
<MyLottie :animationData="lottieJson" />
div>
template>
<script>
import MyLottie from '@/components/MyLottie'
export default {
name: 'Home',
components: {
MyLottie
},
data () {
return {
// lottie json文件
lottieJson: require('@/assets/lottie/lottie.json')
}
}
}
script>
这样一个lottie动画就出来了

下面结合lottie的一些实例方法,将我们的lottie组件添加鼠标事件,官方文档
html部分修改
<div class="lottie" @mouseenter="onMouseenter" @mouseleave="onMouseleave">div>
methods部分修改
methods: {
intLottie () {
let { animationData, autoplay, loop } = this
if (!autoplay) {
// 这里交互播放不循环
loop = false
}
this.lottie = lottie.loadAnimation({
container: this.$el, // 渲染容器
renderer: 'svg', // 渲染方式
loop, // 是否循环
autoplay, // 自动播放
animationData // lottie json文件
})
},
onMouseenter () {
// 我这里demo,非自动播放则判断为鼠标交互播放,具体封装根据自身业务场景来
if (!this.autoplay) {
this.lottie.setDirection(1)
this.lottie.play()
// 监听lottie播放结束
this.lottie.addEventListener('complete', e => {
this.lottie.stop()
})
}
},
onMouseleave () {
this.lottie.removeEventListener('complete')
if (!this.autoplay) {
// 改变播放方向,鼠标移出回退
this.lottie.setDirection(-1)
}
}
}
}
引入组件处修改
<MyLottie :animationData="lottie" :autoplay="false" />
下面是改造后的效果
