Skip to content
Advertisement

Vue.js run a code in mounted and again for restart functionality

I am creating a game in VueJS, where, when the page loads, I want a method to fire, make an ajax call to an external API and create a bunch of data properties. When the player wins the round, I want to them to be able to see a button that allows them to restart the game. I am using a mounted() hook to fire the method on page load.

My question is I am not sure how to implement the restart functionality if the game setup and API call are within the mounted() function. Is there a way to run the mounted() function again?

Advertisement

Answer

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement