How to run code in mounted and again for restart functionality with Vue.js?

Sometimes, we want to run code in mounted and again for restart functionality with Vue.js.

In this article, we’ll look at how to run code in mounted and again for restart functionality with Vue.js.

How to run code in mounted and again for restart functionality with Vue.js?

To run code in mounted and again for restart functionality with Vue.js, we move the code in mounted into its own method.

For instance, we write

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

to define the init method and call it in mounted.

Then we add

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

into our HTML code to call init when we click on the button.

Conclusion

To run code in mounted and again for restart functionality with Vue.js, we move the code in mounted into its own method.