。$ mount()和el [Vue JS]

时间:2017-10-19 13:47:04

标签: vue.js vuejs2

此代码之间的区别是什么:

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

和这一个:

new Vue({
    el: '#app',
    data () {
        return {
            text: 'Hello, World'
        };
    }
})

我的意思是使用.$mount()代替el有什么好处,反之亦然?

4 个答案:

答案 0 :(得分:34)

// 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) 允许您在需要时显式安装Vue实例。这意味着您可以延迟SELECT A, B, C, D, E, F, G, H, I FROM Table UNION ALL ( SELECT A, B, F, G FROM Stuff --JOIN?MERGE?WhatHere? SELECT A, B, E, C FROM otherStuff --JOIN?MERGE?WhatHere? SELECT A, B, D, H FROM otherstuffbis I --adding null value to columns ) 实例的挂载,直到页面中存在特定元素或某些异步过程完成为止,这在将vue添加到将元素注入DOM的旧应用程序时特别有用,I当我想在多个测试中使用相同的vue实例时,我还经常在测试(See Here)中使用它:

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       return CGSize()
    }

这是JSFiddle:https://jsfiddle.net/79206osr/

答案 1 :(得分:14)

根据vm.$mount()上的Vue.js API文档,两者在功能上是相同的,只是$mount 可以(可选)在没有元素选择器的情况下调用,这导致Vue模型与文档分离(因此可以在以后添加)。此示例来自文档:

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 :(得分:3)

在您提供的示例中,我不相信存在太多差异或好处。但是,在其他情况下可能会有一个好处。 (我从未遇到过如下情况)。

  1. 使用$mount(),您可以更灵活地使用它 如果有必要的话,可以安装。

  2. 同样,如果由于某种原因你需要实例化 实际在知道要挂载什么元素之前的实例 (也许是动态创建的元素)然后你可以挂载 稍后使用vm.$mount()

  3. 继上面你可以使用mount时使用mount 需要事先做出决定要安装哪个元素 假设可能存在两种或更多种可能性。
  4. 像...一样的东西。

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

答案 3 :(得分:0)

最佳答案就足够了。刚刚在这里发表评论,因为我的信誉度不足。 Alternativley:

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

   vm.$mount(element);
}, 0)
相关问题