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

新手上路,请多包涵

这段代码有什么区别:

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

和这个:

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

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

原文由 yierstem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 372
2 个回答

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

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

原文由 craig_h 发布,翻译遵循 CC BY-SA 3.0 许可协议

根据 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)

原文由 ContinuousLoad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题