Home > other >  How to launch lottie player animation on click button in vue.js
How to launch lottie player animation on click button in vue.js

Time:10-25

I have a lottie animation json file called congratulations.json. I have included the path of the file inside src in lottie player tag like this:

<lottie-player
        
        src="../../../congratulations.json"
        background="transparent"
        speed="1"
        style="width: 300px; height: 300px"
        loop
        controls
        autoplay
      ></lottie-player>

I want to launch this lottie player animation on click over a button in vue.js.

I have coded like this:

<div >
        <button v-on:click="cong" >
          animation
        </button>
      </div>

methods:{
  cong() {
      <lottie-player
        
        src="../../../congratulations.json"
        background="transparent"
        speed="1"
        style="width: 300px; height: 300px"
        loop
        controls
        autoplay
      ></lottie-player>;
    },
}

But its not working. Do I need to install any addons/extensions or my code is incorrect ?

CodePudding user response:

That doesn't seem like the correct way to do what you want in Vue. I assume you want to show the lottie player when the button is clicked. If so, here is one way to do it:

You can have a boolean variable in the data of the component, e.g. showPlayer which will be initially set to false. Then, you can delete the cong method and have something like this:

<div >
    <button v-on:click="showPlayer = true" >
      animation
    </button>
    <lottie-player
            v-if="showPlayer"
            
            src="**../../../congratulations.json**"
            background="transparent"
            speed="1"
            style="width: 300px; height: 300px"
            loop
            controls
            autoplay
    ></lottie-player>
</div>

Of course, this is only the template code. You need to have the boolean variable in the component's data. The lottie-player tag's attributes should also be correct in order for this to work.

  • Related