You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目使用lottie-web出现内存泄漏问题该如何解决?

lottie-web Vue项目内存泄漏解决方案

你遇到的问题核心原因是没有在组件销毁时主动释放lottie动画实例的相关资源,按以下步骤调整即可解决:

  • 存储动画实例,组件销毁时主动释放
    lottie.loadAnimation方法会返回动画实例,你需要将其存在组件数据中,在组件生命周期销毁钩子中调用实例销毁方法,清空引用方便垃圾回收。
    如果你的项目是Vue2,使用beforeDestroy钩子;Vue3则使用beforeUnmount钩子。调整后的组件示例代码如下:
<template>
    <div ref="animation"></div>
</template>

<script>
import lottie from 'lottie-web';

export default {
    data() {
        return {
            animInstance: null
        }
    },
    mounted() {
        this.animInstance = lottie.loadAnimation({
            container: this.$refs.animation,
            renderer: this.renderer || 'svg', // 优先使用svg渲染器,内存占用远低于canvas
            loop: this.loop,
            autoplay: this.autoplay,
            path: this.path, // 也可替换为animationData配置,逻辑一致
        });
    },
    beforeDestroy() {
        if (!this.animInstance) return
        // 停止动画播放
        this.animInstance.stop()
        // 销毁lottie内部创建的DOM、定时器、渲染上下文等资源
        this.animInstance.destroy()
        // 清空实例引用,等待GC回收
        this.animInstance = null
        // 如果不需要全局缓存动画资源,可调用该方法清空lottie全局缓存
        lottie.clearCache()
    },
    props: { /* 自定义props */ }
}
</script>
  • 特殊场景适配
    如果你的组件使用了keep-alive缓存,需要额外在deactivated钩子中执行上述销毁逻辑,在activated钩子中重新加载动画,避免路由切换时缓存组件的动画实例持续占用内存。

  • 额外优化建议

    • 非必要不要对动画JSON做深拷贝,多组件复用同一个动画时直接复用同一个JSON对象即可,深拷贝只会额外增加内存占用
    • 没有特殊需求优先使用svg渲染器,canvas渲染器会额外占用大量显存和内存,且销毁时更容易出现资源残留
    • 不需要持续播放的动画播放完毕后就主动调用stop()方法,避免后台持续运行占用资源

内容的提问来源于stack exchange,提问作者Adrian Zavis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:15:06