I am working on a Vue3 plugin that generates a toast after some user action on the UI.
I create the toast with createVNode and render and this works great. After 2500ms I would like the toast to disappear from the UI and the Vue component Toast to be destroyed. However I noticed that render(null, container) or document.body.removeChild(container) does actually remove the Toast from the UI and the Toast node from the DOM, it does not destroy the Toast component instance. My concern is that after dozens of Toasts, memory will increase without ever be cleared from the old Toast.
Is there a way in Vue3 to programmatically destroy a component ?
import { createVNode, Plugin, render } from 'vue'
import Alert from './Alert.vue'
const plugin: Plugin = {
// eslint-disable-next-line
install(app, options) {
const toast = {
show(message: string) {
const container = document.createElement('div')
document.body.appendChild(container)
const toastVNode = createVNode(
Alert,
{ message: message },
null
)
render(toastVNode, container)
setTimeout(function () {
render(null, container)
document.body.removeChild(container)
}, 2500);
}
}
app.provide("$Toast", toast);
}
}
export default plugin