Vue JS mounted()

后端 未结 2 679
渐次进展
渐次进展 2020-12-13 06:18

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 play

相关标签:
2条回答
  • 2020-12-13 06:47

    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>
    

    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.

    0 讨论(0)
  • 2020-12-13 07:08

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

    function init() {
      // Use `this` normally
    }
    
    new Vue({
      methods:{
        init
      },
      mounted(){
        init.call(this)
      }
    })
    
    0 讨论(0)
提交回复
热议问题