问题描述
我正在 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?
推荐答案
将您的初始化抽象为一个方法,并从 mounted
和您想要的任何其他地方调用该方法.
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 在挂载中运行代码并再次运行以实现重新启动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!