62

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?

3 Answers 3

117

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.

4
  • Actually it seems everybody recommends to use the created hook rather than mounted to initialize a component. In particular to fetch data. Feb 5, 2019 at 7:51
  • 2
    @Alexis.Rolland I think initiating async code is probably better in created vs mounted. Your choice of which to use is dependent usually on whether you need access to rendered elements or not. In this specific case, I think OP just wanted a strategy for reusing code called from either mounted or created.
    – Bert
    Feb 6, 2019 at 13:05
  • Single Responsibility Principle. Aug 25, 2020 at 13:37
  • It seems the ordering matters. Having the mounted block after the methods works, before it and it doesn't.
    – Arthur
    Nov 3, 2020 at 14:12
4

With Vue 3 and composition API you could use onMounted hook to call a function that could be called later :

import {ref, onMounted, watch} from 'vue'

export default {
  setup() {
    const win=ref(false)

    watch(win,(newVal) => {
      if(newVal) {
        init()
      }
    })

    onMounted(()=>{
      init()
    })

    function init(){
      //init
    }
  }
}

1

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.