$mount
允许您在需要时显式装载Vue实例.这意味着您可以延迟安装vue
实例,直到页面中存在特定元素或某个异步进程完成,这在将vue添加到向DOM中注入元素的旧应用时尤其有用,当我想在多个测试中使用同一个vue实例时,我也经常在测试(See Here)中使用这一点:
// 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)
这里是JSFIDLE:https://jsfiddle.net/79206osr/