您可以在这里找到卸载命令:https://v3.vuejs.org/api/application-api.html#unmount https://v3.vuejs.org/api/application-api.html#unmount
不幸的是,如果您想在应用程序内部执行此操作,文档中没有任何方法可以执行此操作。
然而,在分析了该对象之后,我找到了一种方法。您可以通过使用以下方法来实现它:this.$.appContext.app.unmount();
我不是这个解决方案的忠实粉丝,因为它在未来的版本中不再适用,但它在我的项目中运行良好。
编辑:
另一种方法是延长Vue
对象根据此:https://github.com/vuejs/vue-next/issues/1802 https://github.com/vuejs/vue-next/issues/1802 and https://github.com/pearofducks/mount-vue-component https://github.com/pearofducks/mount-vue-component
我稍微改进了一下功能:
function mount(component, { props, children, element, app } = {}) {
let el = element
let vNode = createVNode(component, props, children)
vNode.destroy = () => {
if (el) render(null, el)
el = null
vNode = null
}
if (app?._context) vNode.appContext = app._context
if (el) render(vNode, el)
else if (typeof document !== 'undefined' ) render(vNode, el = document.createElement('div'))
const destroy = () => {
if (el) render(null, el)
el = null
vNode = null
}
return { vNode, destroy, el }
}
您现在可以跟踪您作为子组件的组件,使用以下命令从父组件和子组件中销毁它:this.$.vnode.destroy();
然而,新的官方方式似乎使用createApp
now.