Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Vue.js在mounted中运行代码,然后再次运行以重新启动功能_Javascript_Vue.js_Model View Controller_Vuejs2_Vuejs3 - Fatal编程技术网

Javascript Vue.js在mounted中运行代码,然后再次运行以重新启动功能

Javascript Vue.js在mounted中运行代码,然后再次运行以重新启动功能,javascript,vue.js,model-view-controller,vuejs2,vuejs3,Javascript,Vue.js,Model View Controller,Vuejs2,Vuejs3,我正在VueJS中创建一个游戏,当页面加载时,我希望启动一个方法,对外部API进行ajax调用,并创建一组数据属性。当玩家赢了这一轮,我希望他们能够看到一个按钮,让他们重新开始游戏。我正在使用mounted()钩子在页面加载时触发该方法 我的问题是,如果游戏设置和API调用在mounted()函数中,我不确定如何实现重启功能。有没有办法再次运行mounted()函数?将初始化抽象为一个方法,并从mounted和其他任何需要的地方调用该方法 new Vue({ methods:{ in

我正在VueJS中创建一个游戏,当页面加载时,我希望启动一个方法,对外部API进行ajax调用,并创建一组数据属性。当玩家赢了这一轮,我希望他们能够看到一个按钮,让他们重新开始游戏。我正在使用
mounted()
钩子在页面加载时触发该方法


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

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

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})
然后在模板中可能有一个按钮重新开始

<button v-if="playerWon" @click="init">Play Again</button>
再次播放

在该按钮中,
playerWon
表示数据中的一个布尔值,当玩家赢得游戏时,您将设置该布尔值,以便按钮出现。您可以在
init

中将其设置回false,也可以将
装入的
移出Vue实例,使其成为顶级作用域中的函数。这也是一个有用的技巧

函数init(){
//通常使用'this'
}
新Vue({
方法:{
初始化
},
安装的(){
初始化调用(此)
}
})

使用Vue 3和composition API,您可以使用
onMounted
钩子调用稍后可以调用的函数:

import {ref, onMounted, watch} from 'vue'
export default{
setup(){
 const win=ref(false)

 watch(win,(newVal)=>{
    if(newVal){
      init()
    }
 })

 onMounted(()=>{
   init()
 })

   function init(){
   //init
    }
 }
}


实际上,似乎每个人都建议使用
创建的
钩子而不是
挂载的
来初始化组件。特别是在获取数据方面。@Alexis.Rolland我认为在created和mounted中启动异步代码可能更好。选择使用哪一个通常取决于是否需要访问渲染元素。在这个特定的例子中,我认为OP只是想要一个策略,用于重用从挂载或创建的调用的代码。单一责任原则。看起来排序很重要。在方法起作用之后、之前和不起作用之前安装块。