我有一个相当大的vue.js 2应用程序,它具有动态选项卡机制。用户可以与应用程序打开和关闭选项卡进行交互,每个选项卡代表一个路由。为了实现这一点,我使用vue路由器并保持活力,如下面的示例。
<template>
<div id="app">
<keep-alive>
<router-view :key="routerViewKey"/>
</keep-alive>
</div>
</template>当用户单击“关闭”选项卡按钮时,将调用$destroy函数从缓存中删除其组件。但是,我正在将这个应用程序从vue 2迁移到vue 3,但是,阅读文档对vue.js 3的最新更改,我们可以看到以下内容:
删除API
$destroy实例方法用户不应再手动管理单个Vue组件的生命周期。
到目前为止,我还没有找到任何替代方案,所以如何以编程方式销毁/卸载vue.js 3中的“保持活动”中缓存的组件。
编辑1(4月/22日):到目前为止,还不可能实现$destroy在vue.js 3中vue.js 2上所做的事情。目前有一个RFC来解决这个问题(https://github.com/vuejs/rfcs/discussions/283),但不幸的是,它已经开放了一年多,没有任何反馈。
发布于 2020-12-23 20:19:56
您可以在这里找到卸载命令: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 }
}现在您可以跟踪您作为子组件拥有的组件,通过使用以下命令从父组件和子组件中销毁它:this.$.vnode.destroy();
然而,新的官方方式似乎现在使用createApp。
发布于 2020-12-06 09:51:14
破坏钩已被卸载取代。我想您可以从复合API导入卸载。
发布于 2021-12-23 16:26:22
尝试使用v-if
<template>
<div
v-if="!close"
:class="`z-50 absolute py-4 mx-4 ${position}`"
data-testid="notification"
>
...
<div v-if="enableClose" class="cursor-pointer absolute right-1 top-3 text-gray-500 text-2xl" @click="onClose">
×
</div>
</Flash>
</div>
</template>
<script lang="ts">
import {defineComponent, render} from "vue";
import Flash from "@/core/shared/components/Layout/Flash.vue";
export default defineComponent({
name: "Toast",
components: {
Flash,
},
props: {
...
enableClose: {
type: Boolean,
default: true,
},
},
computed: {
...
},
data() {
return {
close: false
};
},
methods: {
onClose() {
this.close = true;
},
},
});
</script>https://stackoverflow.com/questions/65163775
复制相似问题