Vue JS mount() [英] Vue JS mounted()
问题描述
我在VueJS中创建一个游戏,当页面加载时,我想要一个方法来触发,对外部API进行ajax调用并创建一堆数据属性。当玩家赢得回合时,我希望他们能够看到一个允许他们重新开始游戏的按钮。我正在使用 mounted()
钩子来激活页面加载时的方法。
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.
我的问题是我不是如果游戏设置和API调用在 mounted()
函数内,请确定如何实现重启功能。有没有办法再次运行 mounted()
函数?
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?
谢谢!
推荐答案
将初始化抽象为方法,并从 mount
中调用该方法以及您想要的任何其他地方。
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>
在此按钮中, playerWon
表示布尔值您在玩家赢得游戏时设置的数据值,以便显示按钮。您可以在 init
中将其设置为false。
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
.
这篇关于Vue JS mount()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!