Accessing a Vue instance outside of its declaration

Published on April 18, 2017 by

Until now, we have done all of our work within the Vue instances themselves. But we can also reference these Vue instances by storing them in variables.

I have prepared a super simple example which just displays a data property.

<div id="vm1">
  <h1>{{ name }}</h1>
</div>
new Vue({
	el: '#vm1',
	data: {
		name: 'Vue Instance #1'
	}
});

Let’s say that after initializing the Vue instance, I want to update the data property. To do this, I can assign the Vue instance to a variable.

var vm1 = new Vue({
	el: '#vm1',
	data: {
		name: 'Vue Instance #1'
	}
});

On this variable, we can access any data properties, methods, etc. directly. We could, for example, read the value of the data property by writing vm1.name.

But let’s change its value instead.

vm1.name = 'Hello from the other side!';

I will just wrap this line within a two second timeout, just so that it is easier for us to see what is going on when running the code.

setTimeout(function() {
	vm1.name = 'Hello from the other side!';
}, 2000);

Running the code, we will see that the output changes after two seconds. This is because Vue.js watches data properties for changes. We will talk about this in more details later in this series, but just know that it makes no difference that we change the values outside of the declaration of the Vue instance. Vue.js will still react to any changes made to the data.

So this is how you can access Vue instances after having declared them. Similarly, you could also have a variable contain an object, which you could then pass to the Vue constructor when initializing the Vue instance. This would allow you to manipulate the data object before initializing the Vue instance and apply whatever logic you may need outside of the instance itself.

Did you notice that we could access the name data property directly without any prefix? This is because of how Vue.js proxies our data as I mentioned a few times before. We will take a more detailed look at this soon, but first let’s see how we can use multiple Vue instances on the same page.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.