Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
张浩杰 committed Aug 24, 2023
1 parent 4c0fcd0 commit 740203e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 14 deletions.
16 changes: 2 additions & 14 deletions src/layout/components/AppMain.vue
Original file line number Diff line number Diff line change
@@ -1,25 +1,13 @@
<script lang="ts" setup>
import { computed } from "vue"
import { useRoute } from "vue-router"
import { useTagsViewStore } from "@/store/modules/tags-view"
const route = useRoute()
const tagsViewStore = useTagsViewStore()
const key = computed(() => {
// 返回 route.path 和 route.fullPath 有着不同的效果,大多数时候 path 更通用
return route.path
})
import { CompConsumer } from "./comp-consumer"
</script>

<template>
<section class="app-main">
<div class="app-scrollbar">
<router-view v-slot="{ Component }">
<transition name="el-fade-in" mode="out-in">
<keep-alive :include="tagsViewStore.cachedViews">
<component :is="Component" :key="key" />
</keep-alive>
<CompConsumer :component="Component" />
</transition>
</router-view>
</div>
Expand Down
56 changes: 56 additions & 0 deletions src/layout/components/comp-consumer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useTagsViewStore } from "@/store/modules/tags-view"
import type { VNode } from "vue"
import { h } from "vue"
import { KeepAlive, cloneVNode, createVNode, defineComponent } from "vue"
import { useRoute } from "vue-router"
interface CompConsumerProps {
component?: VNode
}
const compMap = new Map<string, VNode>()
export const CompConsumer = defineComponent(
(props: CompConsumerProps) => {
const tagsViewStore = useTagsViewStore()
const route = useRoute()
return () => {
const component = props.component
// 判断当前是否包含name,如果不包含name,那就直接处理掉name
if (!route.name) return component
// 获取当前组件的name
const compName = (component?.type as any)?.name
const routeName = route.name as string
let Comp: VNode
if (compMap.has(routeName)) {
// @ts-expect-error this is Node
Comp = compMap.get(routeName)
} else {
const node = cloneVNode(component!)
if (compName && compName === routeName)
// @ts-expect-error this is obj
node.type.name = `__${compName}__` + "CUSTOM_NAME"
// @ts-expect-error this is VNode
// eslint-disable-next-line vue/one-component-per-file
Comp = defineComponent({
name: routeName,
setup() {
return () => node
}
})
compMap.set(routeName, Comp)
}
return createVNode(
KeepAlive,
{
include: tagsViewStore.cachedViews
},
{
default: () => h(Comp)
}
)
}
// eslint-disable-next-line vue/one-component-per-file
},
{
name: "CompConsumer",
props: ["component"]
}
)

0 comments on commit 740203e

Please sign in to comment.