vue使用lottie-web
vue3封装lottie插件
·
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;
}
更多推荐
已为社区贡献2条内容
所有评论(0)