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

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

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

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

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

For instance, we write

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

<script>
//...
export default {
  //...
  methods: {
    init() {
      //...
    },
  },
  mounted() {
    this.init();
  },
  //...
};
</script>

to create the init method that we call in the mounted hook and if we click on the Play Again button.

Conclusion

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