import { onActivated, getCurrentInstance } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
/**
 * @description 进入二级页面缓存当前页面
 * @param detailRouteNames 二级页面路由名称
 * @param activatedFn onActivated触发时执行
 */
export const usePageKeepALive = (detailRouteNames: string[], activatedFn?: Function) => {
  const keepAlive = useKeepAliveStore();
  const proxy = getCurrentInstance()?.proxy;
  onBeforeRouteLeave(to => {
    // 只有跳转到详情页，才缓存页面
    if (detailRouteNames.includes(to.name as string)) {
      keepAlive.addKeepAliveName(proxy?.$options.name as string);
    } else {
      keepAlive.removeKeepAliveName(proxy?.$options.name as string);
    }
  });
  onActivated(() => {
    activatedFn && activatedFn();
  });
};
