<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="cachedViews">
      <component :is="Component"></component>
    </keep-alive>
  </router-view>
</template>

<script setup>
import usePermissionStore from '@/store/modules/permission';

const permissionStore = usePermissionStore();
// 递归判断有 children 往里走找到所有路由对象 meta 的 keepAlive 是 true 的然后返回 meta 同级的 name 名字的值，组成一个数组
const cachedViews = []

watch(
  () => permissionStore.sidebarRouters,
  (newRoutes) => {
    if (newRoutes.length > 0) {
      // 路由加载完成后转换格式
      // 把 hidden: true 的筛选掉
      getKeepAliveName(newRoutes)
    }
  },
  { immediate: true, deep: true }
);

function getKeepAliveName(routes) {
  routes.forEach((item) => {
    if (!item.meta?.noCache && item.name) { // 是否缓存
      cachedViews.push(item.name)
    }
    if (item.children) {
      getKeepAliveName(item.children)
    }
  })
}

</script>
