简体   繁体   中英

Vue, I have used $mount() on a component, is there a way to $unmount() a reference?

I realise this is not how the framework was originally intended to be used. What I'd like to do is programatically mount a component to the page, then programmatically unmount it.

const Component = Vue.extend({
    template: '<div>This works</div>'
})
const c = new Component()
c.$mount()
document.getElementById('app').appendChild(c.$el)

What I'd like to do from here is clean up the component

c.$unmount()
c.$destroy()

Is there something like this that will remove the listeners and perform a full cleanup?

Or can I simply do the following without consequence

document.getElementById('#app').innerHTML = ''

You can call $mount on a new DOM element, append component.$el to #app and remove it after $destroy .

 const component = new Vue({ data() { return { message: "Hello" } }, template: "<p>{{message}}<p>", }); const app = document.getElementById("app"); // Mounting on a empty div created programatically component.$mount(document.createElement("div")); app.appendChild(component.$el); setInterval(() => component.message = "Hello " + Date.now(), 100); setTimeout(() => { // destroying the component and removing it from DOM component.$destroy(); app.removeChild(component.$el); }, 2000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <div id="app"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM