使用Vue3和Typescript实现可复用的路由标签页和面包屑导航组件
<template>
<div class="tabs-breadcrumb">
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
<router-link :to="item.path">{{ item.meta.title }}</router-link>
</el-breadcrumb-item>
</el-breadcrumb>
<el-tabs v-model="activeKey" type="border">
<el-tab-pane v-for="item in tabsList" :key="item.name" :label="item.meta.title" :name="item.name">
<!-- 内容 -->
</el-tab-pane>
</el-tabs>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
export default defineComponent({
setup() {
const route = useRoute();
const router = useRouter();
const activeKey = ref(route.name);
const breadcrumbList = ref<any>([]);
const tabsList = ref<any>([]);
const getBreadcrumb = () => {
let currentRoute = route;
const breadcrumbs: any = [];
while (currentRoute.path !== '/') {
breadcrumbs.push(currentRoute);
currentRoute = currentRoute.matched[0].parent || {};
}
breadcrumbList.value = breadcrumbs.reverse();
};
const getTabs = () => {
const routes = route.matched;
tabsList.value = routes.filter(item => item.meta && item.meta.tab);
};
watch(() => route.name, () => {
activeKey.value = route.name;
getBreadcrumb();
getTabs();
});
getBreadcrumb();
getTabs();
return {
activeKey,
breadcrumbList,
tabsList,
};
},
});
</script>
<style scoped>
.tabs-breadcrumb {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px;
background-color: #fff;
}
</style>
这个代码实例展示了如何在Vue 3和TypeScript中结合Element Plus UI框架使用<router-link>
和<el-tabs>
组件来创建一个面包屑导航和可复用的标签页组件。它使用了Composition API的setup
函数,并通过ref
和watch
来管理状态和响应路由变化。
评论已关闭