.$ mount()和el [Vue JS]之间的区别

yie*_*tem 55 vue.js vuejs2

这段代码有什么区别:

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

还有这个:

new Vue({
    el: '#app',
    data () {
        return {
            text: 'Hello, World'
        };
    }
})
Run Code Online (Sandbox Code Playgroud)

我的意思是使用.$mount()而不是el反之亦然的好处是什么?

cra*_*g_h 54

$mount允许您在需要时显式安装Vue实例.这意味着您可以延迟vue实例的挂载,直到页面中存在特定元素或者某些异步过程完成为止,这在将vue添加到将元素注入DOM的旧应用程序时特别有用,我也使用了这个当我想在多个测试中使用相同的vue实例时经常进行测试(请参阅此处):

// 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)
Run Code Online (Sandbox Code Playgroud)

 

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


Con*_*oad 25

根据Vue.js API文档vm.$mount(),两者在功能上是相同的,除了$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)
Run Code Online (Sandbox Code Playgroud)

  • 好的答案没有被考虑 (2认同)

skr*_*ibe 5

在您提供的示例中,我认为并没有太大的区别或好处。但是,在其他情况下可能会有好处。(我从未遇到过以下情况)。

  1. 有了$mount()更大的灵活性,如果有必要,它将安装在什么元素上。

  2. 同样,如果您出于某种原因需要实例化实例,然后才真正知道将其挂载在哪个元素上(可能是动态创建的元素),则可以稍后使用 vm.$mount()

  3. 遵循上述内容,当您需要事先决定要安装哪个元素时,还可以使用mount来假设可能存在两种或多种可能性。

就像是...

if(document.getElementById('some-element') != null){
      // perform mount here
}
Run Code Online (Sandbox Code Playgroud)