How to make dynamic breadcrumbs in vue.js?

by jasen_gottlieb , in category: Javascript , 5 months ago

How to make dynamic breadcrumbs in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 5 months ago

@jasen_gottlieb 

To create dynamic breadcrumbs in Vue.js, you can use a combination of route navigation guards and a tracked breadcrumb trail object.


Here's a step-by-step guide on how to achieve this:

  1. Create a breadcrumb component that will render the list of breadcrumb links.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<template>
  <nav>
    <ol class="breadcrumbs">
      <li v-for="(crumb, index) in breadcrumbs" :key="index">
        <router-link :to="crumb.path">{{ crumb.label }}</router-link>
      </li>
    </ol>
  </nav>
</template>

<script>
export default {
  data() {
    return {
      breadcrumbs: []
    };
  },
  mounted() {
    this.updateBreadcrumbs();
  },
  watch: {
    $route() {
      this.updateBreadcrumbs();
    }
  },
  methods: {
    updateBreadcrumbs() {
      const matchedRoutes = this.$route.matched;
      this.breadcrumbs = matchedRoutes.map(route => ({
        label: route.meta.title,
        path: route.path
      }));
    }
  }
};
</script>

<style>
.breadcrumbs {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
</style>


  1. Define the breadcrumb metadata in your router configuration.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const routes = [
  {
    path: '/',
    component: Home,
    meta: {
      title: 'Home'
    }
  },
  {
    path: '/about',
    component: About,
    meta: {
      title: 'About Us'
    }
  },
  {
    path: '/contact',
    component: Contact,
    meta: {
      title: 'Contact Us'
    }
  }
]


  1. Add the breadcrumb component to your main App.vue file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<template>
  <div id="app">
    <breadcrumb />
    <router-view />
  </div>
</template>

<script>
import Breadcrumb from './Breadcrumb.vue';

export default {
  components: {
    Breadcrumb
  }
};
</script>


With these steps, you'll have a dynamic breadcrumb component that updates based on the current route in your Vue.js application. Make sure to customize the breadcrumb component and route metadata according to your application's navigation structure.