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

前端 未结 4 2329
北荒
北荒 2020-12-07 14:40

What\'s the difference between this code:

new Vue({
    data () {
        return {
            text: \'Hello, World\'
        };
    }
}).$mount(\'#app\')
         


        
4条回答
  •  情书的邮戳
    2020-12-07 15:19

    $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: '
    I\'m mounted
    ', 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/

提交回复
热议问题