Where to use the main variable of a new vue instance

I'm obviously missing the point somewhere here, but where does one use the main variable of a new vue instance?

I'm new to vue.js (obviously) and whilst reading various documentation I can't help notice that each new vue instance starts with something like var app = new Vue({ but then in the examples I've read this app variable doesn't get referenced again in the js or html. The code works fine without referencing it anywhere.

Could someone please kindly advise on where or why I would use the app variable?

Many thanks

1 answer

  • answered 2017-06-17 19:22 Bert Evans

    It's completely not required to capture the result of new Vue() if you don't need or want to.

    The reason it's done is primarily for testing (ala from the console) or for interaction with external libraries. Because all of the methods and data of the Vue are available on the variable it's possible to call those methods and use that data from outside Vue.

    For example, let's say I have some logic on my page completely outside Vue that has some data I want to use inside my Vue.

    const externalData = {message:"I'm some interesting data."}
    
    const myVueApp = new Vue({
      el: "#app",
      data:{
          message: null
      }
    })
    
    myVueApp.message = externalData.message
    

    Here the code is setting the message property of Vue from outside Vue.

    This is useful primarily when you have existing code, and you are integrating Vue into that existing environment.

    Another scenario is just plain testing. Open your console and run the snippet below. Change the context to the snippet's javascript:

    where to change the console context

    And then type

    app.message = "Hey, this is nifty!"
    

    And the new message will be reflected in the Vue.

    console.clear()
    
    const app = new Vue({
      el: "#testing",
      data:{
        message: "Change me from the console!"
      }
     })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
    
    <div id="testing">
      {{message}}
    </div>