Skip to content

Instantly share code, notes, and snippets.

@nilocoelhojunior
Created November 7, 2019 20:37
Show Gist options
  • Save nilocoelhojunior/522c6695c46a851671edf88d8551a79a to your computer and use it in GitHub Desktop.
Save nilocoelhojunior/522c6695c46a851671edf88d8551a79a to your computer and use it in GitHub Desktop.
Breadcrumb to Nuxtjs
<template>
<ol class="breadcrumb">
<li class="item">
<nuxt-link :to="'/'" class="title">
Home
</nuxt-link>
</li>
<li v-for="(item, i) in crumbs" :key="i" class="item">
<nuxt-link :to="item.to" class="title">
{{ item.title }}
</nuxt-link>
</li>
</ol>
</template>
<script>
import startCase from 'lodash.startcase'
export default {
name: 'Breadcrumb',
computed: {
crumbs () {
const pathArray = this.$route.path.split('/')
pathArray.shift()
const breadcrumbs = pathArray.reduce((breadcrumbArray, path, idx) => {
breadcrumbArray.push({
to: breadcrumbArray[idx - 1]
? '/' + breadcrumbArray[idx - 1].path + '/' + path
: '/' + path,
title: startCase(path)
})
return breadcrumbArray
}, [])
return breadcrumbs
}
}
}
</script>
<style lang="scss" scoped>
</style>
@davidmarkl
Copy link

davidmarkl commented Feb 1, 2021

Really nice. But if the search engine navigates you to something like "example.com/about/" it will create a crumb of "undefined" because it splits at the last "/". To prevent this you could add an if (path) {} around the breadcrumbArray.push().

@dragonslayer77
Copy link

for me breadcrumbArray[idx - 1].path didnt work, i had to change it to breadcrumbArray[idx - 1].title

@shershen08
Copy link

here's a cleaner splitting function I've used https://stackoverflow.com/questions/67104312/using-slice-function-for-breadcrumb-routes
just need to replace

 final.push({
		label: array[i],
		to: `/${array.slice(1,i+1).join('/').toString()}`
	})

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