lottie 动画效果实现及性能优化
前言
官网入口
一、动画效果实现
1、MyLottie 封装成一个公共组件
<template>
<div :id="id" style="display: inline-block;vertical-align: middle;"></div>
</template>
<script>
import lottie from "lottie-web";
export default {
name: "MyLottie",
data() {
return {
id:`lottie_${Math.uuidFast("")}`
};
},
props:{
path:{
type: String,
default: ""
},
loop: {
type: Boolean,
default: false
}
},
mounted() {
console.log(lottie);
lottie.loadAnimation({
container: document.getElementById(this.id),
renderer: "svg",
...Object.assign({
loop: this.loop,
autoplay: true,
path: this.path
}, this.$attrs)
});
},
created() {
},
methods: {
}
};
</script>
<style scoped lang="less">
</style>
2、使用这个公共组件
<template>
<div>
<my-lottie autoplay="false" :path="path" :loop="true" style="cursor: pointer;font-size: 0"></my-lottie>
</div>
</template>
import MyLottie from "_c/MyLottie";
export default {
name: "Home",
components:{ MyLottie },
data() {
return {
path: "https://gitee.com/lingxiu5858/assets/blob/master/json/lottie_deleteMember.json"
};
},
}
二、性能优化
1、公共组件性能优化
<template>
<div :id="id" style="display: inline-block;vertical-align: middle;"></div>
</template>
<script>
import lottie from "lottie-web";
export default {
name: "MyLottie",
title: "这里是页面或组件名字",
data() {
return {
id:`lottie_${Math.uuidFast("")}`
};
},
props:{
animationJSON:[String, Object]
},
mounted() {
this.loadAnimation();
},
created() {
},
methods: {
loadAnimation(){
let { animationJSON } = this;
let lottieBox = null;
let animationParams = { loop: false, autoplay: true };
if(Object.prototype.toString.call(animationJSON) === "[object String]"){
animationParams.path = animationJSON;
}else{
animationParams.animationData = animationJSON;
}
console.log("加载动画需要的参数", animationParams);
lottieBox = lottie.loadAnimation({
container: document.getElementById(this.id),
renderer: "svg",
...Object.assign(animationParams, this.$attrs)
});
lottieBox["addEventListener"]("DOMLoaded", () => {
let animationData = JSON.stringify(lottieBox.animationData);
if(Object.prototype.toString.call(animationJSON) === "[object String]"){
localStorage.setItem(lottieBox.fileName, animationData);
}
});
}
}
};
</script>
<style scoped lang="less">
</style>
2、外部使用优化后的公共组件
<template>
<div>
<button @click="openAnimation" />
<my-lottie autoplay="false" :path="path" :loop="true" :animationJSON="animationJSON" style="cursor: pointer;font-size: 0"></my-lottie>
</div>
</template>
import MyLottie from "_c/MyLottie";
export default {
name: "Home",
components:{ MyLottie },
data() {
return {
path: "https://gitee.com/lingxiu5858/assets/blob/master/json/lottie_deleteMember.json"
};
},
methods: {
openAnimation(){
this.animationJSON = this.getStorage(this.path);
},
getStorage(path){
let arr = path.split("/");
let fileName = arr[arr.length - 1].split(".")[0];
let localStorageAnimation = localStorage.getItem(fileName);
return localStorageAnimation ? JSON.parse(localStorageAnimation) : path;
},
}
}