refactor: BreadCrumb Component

This commit is contained in:
pany 2022-08-23 11:13:55 +08:00
parent 487ceb002a
commit 0177b58f16

View File

@ -1,29 +1,29 @@
<script lang="ts" setup> <script lang="ts" setup>
import { onBeforeMount, reactive, watch } from "vue" import { ref, watch } from "vue"
import { useRoute, useRouter, RouteLocationMatched } from "vue-router" import { useRoute, useRouter, RouteLocationMatched } from "vue-router"
import { compile } from "path-to-regexp" import { compile } from "path-to-regexp"
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const breadcrumbs = ref<RouteLocationMatched[]>([])
const getBreadcrumb = () => {
breadcrumbs.value = route.matched.filter((item) => {
return item.meta && item.meta.title && item.meta.breadcrumb !== false
})
}
const pathCompile = (path: string) => { const pathCompile = (path: string) => {
const { params } = route const { params } = route
const toPath = compile(path) const toPath = compile(path)
return toPath(params) return toPath(params)
} }
const state = reactive({ const handleLink = (item: RouteLocationMatched) => {
breadcrumbs: [] as Array<RouteLocationMatched>,
getBreadcrumb: () => {
const matched = route.matched.filter((item) => item.meta && item.meta.title)
state.breadcrumbs = matched.filter((item) => {
return item.meta && item.meta.title && item.meta.breadcrumb !== false
})
},
handleLink(item: any) {
const { redirect, path } = item const { redirect, path } = item
if (redirect) { if (redirect) {
router.push(redirect).catch((err) => { router.push(redirect as string).catch((err) => {
console.warn(err) console.warn(err)
}) })
return return
@ -32,7 +32,6 @@ const state = reactive({
console.warn(err) console.warn(err)
}) })
} }
})
watch( watch(
() => route.path, () => route.path,
@ -40,23 +39,21 @@ watch(
if (path.startsWith("/redirect/")) { if (path.startsWith("/redirect/")) {
return return
} }
state.getBreadcrumb() getBreadcrumb()
} }
) )
onBeforeMount(() => { getBreadcrumb()
state.getBreadcrumb()
})
</script> </script>
<template> <template>
<el-breadcrumb class="app-breadcrumb"> <el-breadcrumb class="app-breadcrumb">
<transition-group name="breadcrumb"> <transition-group name="breadcrumb">
<el-breadcrumb-item v-for="(item, index) in state.breadcrumbs" :key="item.path"> <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
<span v-if="item.redirect === 'noRedirect' || index === state.breadcrumbs.length - 1" class="no-redirect">{{ <span v-if="item.redirect === 'noRedirect' || index === breadcrumbs.length - 1" class="no-redirect">
item.meta.title {{ item.meta.title }}
}}</span> </span>
<a v-else @click.prevent="state.handleLink(item)"> <a v-else @click.prevent="handleLink(item)">
{{ item.meta.title }} {{ item.meta.title }}
</a> </a>
</el-breadcrumb-item> </el-breadcrumb-item>