How to implement a breadcrumb navigation with dynamic links in Vue.js



Image not found!!


Implementing breadcrumb navigation with dynamic links in Vue.js involves creating a reusable breadcrumb component and dynamically updating it based on the current route. Here's a step-by-step guide on how to achieve this:

  1. Create a Breadcrumb Component: First, create a new Vue.js component for the breadcrumb navigation.
html
<!-- Breadcrumb.vue --> <template> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <router-link :to="{ path: '/' }">Home</router-link> </li> <li v-for="(crumb, index) in crumbs" :key="index" class="breadcrumb-item"> <router-link :to="crumb.path">{{ crumb.label }}</router-link> </li> </ol> </nav> </template> <script> export default { data() { return { crumbs: [] }; }, watch: { '$route': 'generateCrumbs' }, mounted() { this.generateCrumbs(); }, methods: { generateCrumbs() { const routes = this.$route.matched; this.crumbs = routes.map(route => { return { label: route.meta && route.meta.breadcrumb || route.name, path: route.path }; }); } } } </script> <style> /* Add your breadcrumb styles here */ </style>
  1. Define Routes with Breadcrumbs: When defining your routes, make sure to include metadata for breadcrumbs.
javascript
// router/index.js import Vue from 'vue'; import Router from 'vue-router'; import Home from '@/views/Home.vue'; import About from '@/views/About.vue'; import Contact from '@/views/Contact.vue'; Vue.use(Router); const routes = [ { path: '/', name: 'Home', component: Home, meta: { breadcrumb: 'Home' } }, { path: '/about', name: 'About', component: About, meta: { breadcrumb: 'About Us' } }, { path: '/contact', name: 'Contact', component: Contact, meta: { breadcrumb: 'Contact Us' } } ]; export default new Router({ mode: 'history', base: process.env.BASE_URL, routes });
  1. Use Breadcrumb Component: Finally, include the breadcrumb component in your layout or any component where you want to display it.
html
<!-- Any.vue --> <template> <div> <Breadcrumb /> <!-- Your content goes here --> </div> </template> <script> import Breadcrumb from '@/components/Breadcrumb.vue'; export default { components: { Breadcrumb } } </script>

This setup will dynamically generate breadcrumb links based on the route hierarchy and display them in your Vue.js application. Make sure to customize the styles according to your design requirements.