Vue.js在挂载后再次运行代码以重新启动功能 [英] Vue.js run a code in mounted and again for restart functionality

查看:64
本文介绍了Vue.js在挂载后再次运行代码以重新启动功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VueJS中创建一个游戏,在该页面中,当页面加载时,我想触发一个方法,对外部API进行ajax调用并创建大量数据属性.当玩家赢得回合时,我希望他们能够看到一个允许他们重新开始游戏的按钮.我正在使用 mount()挂钩在页面加载时触发该方法.

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在挂载后再次运行代码以重新启动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆