104

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?

5 Answers 5

97

$mount allows you to explicitly mount the Vue instance when you need to. This means that you can delay the mounting of your vue 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:

// Create the vue instance but don't mount it
const vm = new Vue({
  template: '<div>I\'m mounted</div>',
  created(){
    console.log('Created');
  },
  mounted(){
    console.log('Mounted');
  }
});

// Some async task that creates a new element on the page which we can mount our instance to.
setTimeout(() => {
   // Inject Div into DOM
   var div = document.createElement('div');
   div.id = 'async-div';
   document.body.appendChild(div);

  vm.$mount('#async-div');
},1000)

 

Here's the JSFiddle: https://jsfiddle.net/79206osr/

Sign up to request clarification or add additional context in comments.

Comments

46

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:

var MyComponent = Vue.extend({
  template: '<div>Hello!</div>'
})
// create and mount to #app (will replace #app)
new MyComponent().$mount('#app')

// the above is the same as:
new MyComponent({ el: '#app' })
// or, render off-document and append afterwards:
var component = new MyComponent().$mount()
document.getElementById('app').appendChild(component.$el)

2 Comments

If you used the vue subclass (Vue.extend) with el, you get in the console: [Vue warn]: option "el" can only be used during instance creation with the new keyword. .$mount not show this warning.
This is exactly what I was looking for to not replace the mount element, thanks!
8

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).

  1. With $mount() you have more flexibility what element it will be mounted on if that were to ever be necessary.

  2. 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()

  3. Following along with the above you could use also use mount when you need to make a decision before hand which element to mount to assuming that there may be two or more possibilities.

Something like...

if(document.getElementById('some-element') != null){
      // perform mount here
}

Comments

1

Top answer is good enough. just left a comment here as I don't have enough reputation points. Alternativley:

 setTimeout(() => {
   const element = document.createElement('div');
   document.body.appendChild(element);

   vm.$mount(element);
}, 0)

Comments

0

Besides all the great answers here that say using $mount is better, another thing I would like to add is about the correctness of your code for when it gets evaluated by clean-code-tools (like SonarQube etc).
In short, the code is cleaner when using $mount separately. Because otherwise the clean-code-tools complains:

"Objects should not be created to be dropped immediately without being used"

So in this example the clean-code-tool complains:

new Vue({
    el: '#some-id',
    ...
})

The solution is:

let instance = new Vue({
    ...
})
instance.$mount('#some-id')

And so everybody is happy again

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.