.$mount() 和 el 的区别 [Vue JS] [英] Difference between .$mount() and el [Vue JS]
问题描述
这段代码有什么区别:
new Vue({
data () {
return {
text: 'Hello, World'
};
}
}).$mount('#app')
还有这个:
new Vue({
el: '#app',
data () {
return {
text: 'Hello, World'
};
}
})
我的意思是使用 .$mount()
而不是 el
有什么好处,反之亦然?
I mean what's the benefit in using .$mount()
instead of el
or vice versa?
推荐答案
$mount
允许您在需要时显式挂载 Vue 实例.这意味着您可以延迟 vue
实例的安装,直到页面中存在特定元素或某些异步进程完成,这在将 vue 添加到将元素注入到DOM,我在测试中也经常使用它(参见此处),当我想在多个测试中使用相同的 vue 实例时:
$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)
这是 JSFiddle:https://jsfiddle.net/79206osr/
Here's the JSFiddle: https://jsfiddle.net/79206osr/
这篇关于.$mount() 和 el 的区别 [Vue JS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!