Skip to content

Instantly share code, notes, and snippets.

@lukeocodes
Last active April 2, 2024 14:01
Show Gist options
  • Save lukeocodes/9bdc3366c852809dddbe4d6eb32188d6 to your computer and use it in GitHub Desktop.
Save lukeocodes/9bdc3366c852809dddbe4d6eb32188d6 to your computer and use it in GitHub Desktop.
A breadcrumbs component for Nuxt3
<script lang="ts" setup>
const route = useRoute();
const router = useRouter();
const getBreadcrumbs = () => {
const fullPath = route.path;
const requestPath = fullPath.startsWith("/")
? fullPath.substring(1)
: fullPath;
const crumbs = requestPath.split("/");
const breadcrumbs = [];
let path = "";
crumbs.forEach((crumb) => {
if (crumb) {
path = `${path}/${crumb}`;
const breadcrumb = router.getRoutes().find((r) => r.path === path);
if (breadcrumb) {
breadcrumbs.push(breadcrumb);
}
}
});
return breadcrumbs;
};
const ariaCurrent = (index) =>
index === getBreadcrumbs().length - 1 ? "page" : "false";
</script>
<template>
<nav id="breadcrumbs" aria-label="Breadcrumb">
<ul>
<li>
<NuxtLink to="/" :aria-current="ariaCurrent(-1)">Home</NuxtLink>
</li>
<li v-for="(breadcrumb, index) in getBreadcrumbs()" :key="index">
<NuxtLink :to="breadcrumb.path" :aria-current="ariaCurrent(index)">
{{ breadcrumb.meta.title }}
</NuxtLink>
</li>
</ul>
</nav>
</template>
@devzom
Copy link

devzom commented Feb 5, 2022

Great one, thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment