Mounting Vue.js Templates Dynamically
Until now, we have always used the el property within our Vue instances to specify which HTML element our Vue instance should control. Or, more formally, which element the Vue instance should be mounted to. This means that we have to know which element the Vue instance should be mounted to when we declare the Vue instance, but we may not always know this. Therefore it is possible to mount the template dynamically, by using a method on the Vue instance. Let’s start with the following code and change it as we go along.
<div id="app">
<h1>{{ message }}</h1>
</div>
var vm = new Vue({
el: '#app',
data: {
message: 'Hello World!'
}
});
Let’s first remove the el property, because we are no longer going to need that, as we are going to mount the template somehow else.
var vm = new Vue({
data: {
message: 'Hello World!'
}
});
If we run the code, we will see that the curly brackets from the string interpolation are displayed, because Vue is no longer controlling the app element.
The Vue instance is now in an unmounted state, because it has no DOM element associated with it. We will get back to this later in this series when we talk about the lifecycle of Vue instances.
We can now call the $mount method on the Vue instance and pass in the same CSS selector as with the el property.
vm.$mount('#app');
This essentially does the same thing as the el property; it’s just a way of manually initiating the mounting of an unmounted Vue instance. When we use the el property, this happens for us behind the scenes.
Now we see the message being output correctly.
Instead of passing in a CSS selector as the argument to the $mount method, we can actually pass in a native DOM element instead. Let’s comment out our current template mount and see what it looks like.
//vm.$mount('#app');
vm.$mount(document.getElementById('app'));
Running the code now will give us the same result.
So mounting the template with the $mount method, is useful if you don’t know which element the Vue instance should be mounted to at the time of instantiating the instance. If you do know this, then you should stick with the el property, as that’s the most common approach. So if you can determine which element to mount to when creating the Vue instance, then you should just mount it immediately. Remember that you can pass a string variable to the el property if you need to apply some logic to determine the CSS selector.
If you need to create a Vue instance and then mount it later – for whatever reason – then use the $mount method. This method gives some additional flexibility, such as defining an inline template within the Vue instance, which we’ll take a look at next.
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!