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
.
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
}
}
}
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)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With