javascript - Vue.js - 删除从 keep-alive 加载的子组件

标签 javascript typescript vue.js vue-router

我的问题类似于此处列出的问题:
Vue.js - Destroy a cached component from keep alive
我还使用 Vue 路由器创建了一种选项卡系统,因此代码如下所示:

//My Tab component 
<template>
  <tab>
    <tab-selector />
    <keep-alive>
      <router-view />
      <!-- This router view is used to render one of the childRoutes of the main TabRoute -->
    </keep-alive> 
  </tab>
</template>

<script>
 handleTabClose() {
   //Close tab logic
   this.$destroy(); 
   //Insert router push to be one of the other tabs that have not been closed.
 }
</script>
vue-router 使用的路由的轮廓如下所示:
    {
        path: "/tab",
        name: "TabComponent",
        component: () => import("InsertComponentPath"),
        children: [{TabRoute1, TabRoute2, TabRoute3}]
    },
在切换选项卡(切换子路由)时使用保持事件状态来维护状态。
我想在关闭选项卡但使用 this.$destroy 时从缓存中删除 childRoute/Component在我的选项卡组件中,它似乎正在破坏整个选项卡组件,而不是其中的子组件。
这个问题和其他堆栈溢出问题中还说明的 V-if 解决方案将不起作用,因为我只想从内存中删除这个特定的选项卡,这会删除所有选项卡。
谢谢你的帮助。

最佳答案

我找到了使用 include 的解决方案keep-Alive 中的参数 https://v2.vuejs.org/v2/api/#keep-alive
我使用 router.getmatchedcomponents() 保留了一组当前事件的标签。获取当前打开的选项卡的组件名称。
然后在我的handleClose()函数,我从 include 中删除已关闭的选项卡大批。
最终实现看起来有点像这样:

//My Tab component 
<template>
  <tab>
    <tab-selector />
    <keep-alive :include="cacheArr">
      <router-view />
      <!-- This router view is used to render one of the childRoutes of the main TabRoute -->
    </keep-alive> 
  </tab>
</template>

<script>
 private cacheArr = []

//Called whenever a new tab is opened
 handleOpen() {
   //Add current Tab to this.cachArr
   this.cachArr.push(router.getmatchedcomponents().pop().name);
 }

//Called whenever new tab is closed.
 handleTabClose(name) {
   //Close tab logic
   
   //Remove Tab being closed from this.cacheArr
   this.cacheArr.splice(this.cacheArr.indexOf(name), 1);
 }
</script>

关于javascript - Vue.js - 删除从 keep-alive 加载的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67180234/

相关文章:

javascript - 切换折叠菜单始终打开

javascript - jQuery 发布到 PHP 无法正常工作,没有任何错误

javascript - angularjs toastr 无法从粘性更改为动态关闭

laravel - Vue 组件未显示/更新

javascript - 具有直接关系的 Vue.js 变量

javascript - 这不是调用我的 obj 函数的正确方法吗?

javascript - react typescript |如何使用 tailwind 启用暗模式?

typescript - 如何导入力矩类型定义

angular - 动态更改 Angular 12 中垫子对话框的宽度/高度

css - Vuetify v-btn 水平向右