<template>
<div class="tabs-breadcrumbs">
<div class="tabs">
<router-link
v-for="route in routes"
:key="route.path"
:to="route.path"
:class="{ active: route.path === currentRoutePath }"
>
{{ route.meta.title }}
</router-link>
</div>
<div class="breadcrumbs">
<!-- 这里使用了Vue 3的组合式API -->
<router-link to="/">Home</router-link>
<span v-for="(crumb, index) in currentBreadcrumbs" :key="index">
<router-link :to="crumb.path">{{ crumb.meta.title }}</router-link>
<span v-if="index !== currentBreadcrumbs.length - 1">/</span>
</span>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
export default defineComponent({
setup() {
const router = useRouter();
const route = useRoute();
const currentRoutePath = ref(route.path);
const currentBreadcrumbs = ref<any[]>([]);
const routes = router.getRoutes().filter((r) => r.meta && r.meta.tab);
const updateBreadcrumbs = () => {
const pathElements = route.path.split('/').filter((e) => e);
currentBreadcrumbs.value = pathElements.reduce((acc, curr) => {
const route = router.getRoutes().find((r) => r.path.endsWith(`/${curr}`));
if (route) acc.push(route);
return acc;
}, [] as any[]);
};
onMounted(() => {
updateBreadcrumbs();
});
onUnmounted(() => {
currentRoutePath.value = '';
currentBreadcrumbs.value = [];
});
watch(() => route.path, () => {
currentRoutePath.value = route.path;
updateBreadcrumbs();
});
return {
routes,
currentRoutePath,
currentBreadcrumbs,
};
},
});
</script>
<style scoped>
.tabs-breadcrumbs {
display: flex;
justify-content: space-between;
}
.tabs, .breadcrumbs {
display: flex;
}
.tabs router-link, .breadcrumbs router-link {
text-decoration: none;
margin-right: 10px;
}
.tabs router-link.act
评论已关闭