Home > Enterprise >  How can I Build Dynamic Breadcrumbs Component base on current Route/URL?
How can I Build Dynamic Breadcrumbs Component base on current Route/URL?

Time:12-21

I'm trying to build a Breadcrumbs component dynamically generating link base on my current URL


Ex.

http://localhost:8080/car/create

My Breadcrumbs should look like

Home > car > create


Ex.

http://localhost:8080/car/ford

My Breadcrumbs should look like

Home > car > ford


Ex.

http://localhost:8080/car/ford/raptor   

My Breadcrumbs should look like

Home > car > ford > raptor

How would one dynamically build sth like this ?


I have

<template lang="">
    <v-row>
            <v-breadcrumbs :items="links" >
                <template v-slot:divider>
                    <v-icon>mdi-chevron-right</v-icon>
                </template>
            </v-breadcrumbs>
        </v-row>
</template>
<script>
export default {
    name: 'Breadcrumbs',
    props: {
        title: String
    },
    data() {
        return {
            links: [
                {
                    text: 'Home',
                    disabled: false,
                    href: '/'
                },
                {
                    text: this.title,
                    disabled: true,
                    href: 'breadcrumbs_link_2'
                }
            ]
        }
    }
}
</script>

CodePudding user response:

You need to implement a computed property like the following:

const breadcrumb = Vue.component('breadcrumb', {
  template: '#breadcrumb',
  props: { title: String },
  computed: {
    links: function() {
      return [ 
        { text: 'Home', disabled: false, href: '/' }, 
        { text: this.title, disabled: true, href: 'breadcrumbs_link_2' },
        ...(
          (new URL(window.location.href))
            .pathname
            .split('/')
            .slice(1)
            .map(seg => ({ text: seg, disabled: false, href: seg }))
        )
      ]; 
    }
  }
});

new Vue({ el:"#app", vuetify: new Vuetify(), components: { breadcrumb } });
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">

<template id="breadcrumb">
  <v-row>
    <v-breadcrumbs :items="links" >
      <template v-slot:divider><v-icon>mdi-chevron-right</v-icon></template>
    </v-breadcrumbs>
  </v-row>
</template>

<v-app id="app">
  <breadcrumb title="title_1" />
</v-app>

  • Related