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

在Vue.js中如何实现点击按钮触发Lottie Player动画

问题原因及解决方案

1. 核心写法错误

你在cong方法内直接编写<lottie-player>标签的写法不符合Vue语法规范:methods 中存放的是JS业务逻辑,无法直接解析HTML模板并插入到DOM中,这段代码属于非法JS语法,自然无法生效。

2. 依赖安装确认

你需要先安装引入lottie-player组件:
执行npm安装命令:
npm install @lottiefiles/lottie-player
安装完成后在当前使用组件文件或者全局main.js中引入注册:

import '@lottiefiles/lottie-player';

3. 正确实现代码

提供两种常用实现方案:

方案1:点击按钮后才加载并播放动画

通过v-if控制组件渲染,渲染时自带autoplay属性自动触发播放:

<template>
  <div>
    <div class="justify-content-center">
      <button @click="cong" class="btn">
        animation
      </button>
    </div>
    <lottie-player
      v-if="showAnimation"
      class="justify-content-center"
      src="../../../congratulations.json"
      background="transparent"
      speed="1"
      style="width: 300px; height: 300px"
      loop
      controls
      autoplay
    ></lottie-player>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showAnimation: false
    }
  },
  methods: {
    cong() {
      this.showAnimation = true
    }
  }
}
</script>

方案2:提前加载动画,默认暂停,点击后触发播放

提前渲染组件不加autoplay属性,点击时调用组件实例的play方法:

<template>
  <div>
    <div class="justify-content-center">
      <button @click="cong" class="btn">
        animation
      </button>
    </div>
    <lottie-player
      ref="lottiePlayer"
      class="justify-content-center"
      src="../../../congratulations.json"
      background="transparent"
      speed="1"
      style="width: 300px; height: 300px"
      loop
      controls
    ></lottie-player>
  </div>
</template>

<script>
export default {
  methods: {
    cong() {
      this.$refs.lottiePlayer.play()
    }
  }
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:36:04