首页 > 解决方案 > 如何在 NuxtJS 中使用 lottie 来实现悬停、单击和所有功能?

问题描述

我正在使用“ vue-lottie ”包,关于如何使用它的信息不多。

我从Lordicons获得了 JSON 动画,它显示正确,但我无法使动画在悬停或单击时工作,只能循环或静态(无动画)。

我的组件:

<template>
  <div>
    <lottie
      :options="lottieOptions"
      :width="50"
    />
  </div>
</template>

<script>
import lottie from "vue-lottie/src/lottie.vue";
import * as animationData from "~/assets/about.json";

export default {
  components: {
    lottie
  },
  data() {
    return {
      anim: null, // for saving the reference to the animation
      lottieOptions: {
        animationData: animationData.default,
        loop: false,
        autoplay: false,
      }
    };
  },
  methods: {
    handleAnimation(anim) {
      this.anim = anim;
    },
    stop() {
      this.anim.stop();
    },
    play() {
      this.anim.play();
    },
    pause() {
      this.anim.pause();
    },
  }
};
</script>

我只在页面上使用导入组件:

...

<AboutIcon />

...

<script>

import AboutIcon from "~/components/AboutIcon.vue";

export default {
  components: {
    AboutIcon,
  },
  data() {
    return {};
  }
};
</script>

标签: vue.jsnuxt.jslottie

解决方案


从您提供的代码示例中,您忘记附加@animCreated="handleAnimation"事件。

所以this.anim实际上总是空的。

<template>
  <div>
    <lottie
      :options="lottieOptions"
      :width="50"
      @animCreated="handleAnimation"
    />
  </div>
</template>

然后您只需设置 a@mouseover="play"即可在悬停时启动动画。


推荐阅读