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

Vue中anime.js点击事件不生效的问题排查

解决anime.js点击按钮无法触发动画的问题

嘿,我帮你找到问题所在啦!先拆解下你的代码问题,再给你两种可行的解决办法:

问题分析

页面加载时动画正常,点击按钮却没反应,核心出在这两个点:

  1. 按钮绑定的@click="testClickGo().restart"逻辑有误:每次点击都会调用testClickGo()创建一个全新的动画实例,这个新实例刚创建还没启动过,调用restart根本不会触发动画——restart是用来重置已经运行过的动画实例的。
  2. 就算新实例能执行,第一次动画跑完后,目标元素h1已经处于translateX:200的状态了,新动画的起始值和结束值一致,视觉上完全看不到变化。

先贴一下你的原始代码方便对照:

<template>
  <div class="compHeader">
    <h1 class="testVal" style="position: absolute;">QWERTY</h1>
    <button type="button" class="testClick" @click="testClickGo().restart">+</button>
  </div>
</template>

<script>
export default {
  methods: {
    testClickGo(){
      console.log(111);
      return this.$anime({
        targets: '.testVal',
        translateX: 200,
        delay: 800
      });
    }
  },
  mounted(){
    this.testClickGo();
  }
}
</script>

解决方案

方案1:复用同一个动画实例(推荐)

把动画实例存在组件的data里,不管是页面加载还是点击按钮都用同一个实例,点击时直接调用restart就能重置并重新播放动画:

<template>
  <div class="compHeader">
    <h1 class="testVal" style="position: absolute;">QWERTY</h1>
    <button type="button" class="testClick" @click="testClickGo">+</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      animeInstance: null // 用来保存动画实例
    }
  },
  methods: {
    testClickGo(){
      console.log(111);
      if (!this.animeInstance) {
        // 第一次创建实例,默认不自动播放(按需调整)
        this.animeInstance = this.$anime({
          targets: '.testVal',
          translateX: 200,
          delay: 800,
          autoplay: false
        });
        // 页面加载时自动播放动画
        this.animeInstance.play();
      } else {
        // 点击按钮时重启动画
        this.animeInstance.restart();
      }
    }
  },
  mounted(){
    this.testClickGo();
  }
}
</script>

方案2:每次点击创建新动画,先重置元素状态

如果你希望每次点击都生成新的动画实例,那要在创建动画前先把目标元素的位置重置,这样新动画才有视觉变化:

<template>
  <div class="compHeader">
    <h1 class="testVal" style="position: absolute;">QWERTY</h1>
    <button type="button" class="testClick" @click="testClickGo">+</button>
  </div>
</template>

<script>
export default {
  methods: {
    testClickGo(){
      console.log(111);
      // 先把元素位置重置回初始状态
      this.$anime.set('.testVal', { translateX: 0 });
      // 再创建并执行新动画
      return this.$anime({
        targets: '.testVal',
        translateX: 200,
        delay: 800
      });
    }
  },
  mounted(){
    this.testClickGo();
  }
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:27:38