mar*_*atg 7 vue.js vue-router vuejs3
我有一个相当大的vue.js 2应用程序,它具有动态选项卡机制。用户可以与应用程序打开和关闭选项卡进行交互,每个选项卡代表一条路线。为了实现这一点,我使用 vue router 并保持活动状态,如下例所示。
<template>
<div id="app">
<keep-alive>
<router-view :key="routerViewKey"/>
</keep-alive>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
当用户单击关闭选项卡按钮时,$destroy将调用该函数以从缓存中删除其组件。我正在将此应用程序从 vue 2 迁移到 vue 3,但是,阅读 vue.js 3 的重大更改文档我们可以看到:
删除的 API
$destroy实例方法。用户不应再手动管理各个 Vue 组件的生命周期。
到目前为止我还没有找到任何替代方案,那么如何以编程方式销毁/卸载vue.js 3中 keep-alive 内的缓存组件?
编辑 1(4 月 22 日):到目前为止,仍然无法$destroy在 vue.js 3 中实现 vue.js 2 上的功能。目前有一个 RFC 可以解决此问题(https://github.com/vuejs/rfcs/ Discuss/283),但不幸的是它已经开放一年多了,没有任何反馈。
您可以在此处找到卸载命令: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/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 }
}
Run Code Online (Sandbox Code Playgroud)
您现在可以跟踪您作为子组件的组件,使用以下命令从父组件和子组件中销毁它:this.$.vnode.destroy();
不过createApp现在官方好像用的是新的方式。