Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vue.js - Difference between .$mount() and el [Vue JS]

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...