Javascript Vue JS 挂载()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45021907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:52:31  来源:igfitidea点击:

Vue JS mounted()

javascriptvue.jsmodel-view-controllervuejs2reusability

提问by lnamba

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.

我正在 VueJS 中创建一个游戏,当页面加载时,我想要一个方法来触发,对外部 API 进行 ajax 调用并创建一堆数据属性。当玩家赢得这一轮时,我希望他们能够看到一个按钮,允许他们重新开始游戏。我正在使用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?

我的问题是,如果游戏设置和 API 调用在mounted()函数内,我不确定如何实现重启功能。有没有办法mounted()再次运行该功能?

回答by Bert

Abstract your initialization into a method, and call the method from mountedand wherever else you want.

将您的初始化抽象为一个方法,并从mounted您想要的任何其他地方调用该方法。

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, playerWonrepresents 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.

在此按钮中,playerWon代表您数据中的一个布尔值,您将在玩家赢得游戏时设置该值,以便显示该按钮。您将在 中将其设置回 false init

回答by vkarpov15

You can also move mountedout 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.

您还可以移出mountedVue 实例并使其成为顶级作用域中的函数。这也是Vue 中服务端渲染的一个有用技巧。

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})