What's the difference between this code:
new Vue({
data () {
return {
text: 'Hello, World'
};
}
}).$mount('#app')
and this one:
new Vue({
el: '#app',
data () {
return {
text: 'Hello, World'
};
}
})
I mean what's the benefit in using .$mount()
instead of el
or vice versa?
$mount
allows you to explicitly mount the Vue instance when you need to. This means that you can delay the mounting of yourvue
instance until a particular element exists in your page or some async process has finished, which can be particularly useful when adding vue to legacy apps which inject elements into the DOM, I've also used this frequently in testing (See Here) when I've wanted to use the same vue instance across multiple tests:Here's the JSFiddle: https://jsfiddle.net/79206osr/
In the example you provide, I don't believe there is really much difference or benefit. However, in other situations there may be a benefit. (I have never encountered situations like the following).
With
$mount()
you have more flexibility what element it will be mounted on if that were to ever be necessary.Similarly you if for some reason you need to instantiate the instance before you actually know what element it will be mounted on (maybe an element that is created dynamically) then you could mount it later using
vm.$mount()
Something like...
According to the Vue.js API docs on
vm.$mount()
, the two are functionally the same, except that$mount
can (optionally) be called without an element selector, which causes the Vue model to be rendered separate from the document (so it can be appended later). This example is from the docs: