steffen-wirth
3/17/2020 - 1:43 PM

Vue 2 - VueRouter - Simple Dynamic breadcrumbs + Microdata

Vue 2 - VueRouter - Simple Dynamic breadcrumbs + Microdata

export default {

        beforeRouteEnter(route, redirect, next) {
            next(vm => {
                vm.$http.get(`${API.BASE}/${API.PAGE}/${route.name}`).then((response) => {
                    vm.page = response.data.page;

                    vm.eventHub.$emit('update-breadcrumb', [
                        {
                            title: 'Home',
                            link: {
                                name: 'home.index'
                            }
                        }, {
                            title: vm.page.title,
                            link: {
                                name: vm.page.slug,
                                slug: null // optional slug goes here i.e. 1 would result in matching the route: /page/:slug, so it'll output /page/1
                            }
                        }
                    ]);
                });
            });
        },
        
}
<nav class="breadcrumbs" v-if="breadcrumb.length" itemscope="itemscope" itemtype="http://schema.org/Breadcrumb">
    <ul class="breadcrumb" itemscope="itemscope" itemtype="http://schema.org/BreadcrumbList">

        <router-link v-for="(crumb, i) in breadcrumb" :to=" crumb.link "
            tag="li"
            active-class="active"
            class="breadcrumb-item"
            itemprop="itemListElement" itemscope="itemscope" itemtype="http://schema.org/ListItem"
        >
            <a itemprop="item">
                <span itemprop="name">{{ crumb.title }}</span>
            </a>
        </router-link>

    </ul>
</nav>
export default {
    mounted: function () {

    },

    computed: {

    },

    data: function () {
        return {
            breadcrumb: []
        }
    },

    created: function () {
        this.eventHub.$on('update-breadcrumb', data => {
            this.updateBreadcrumb(data);
        });
    },

    methods: {

        updateBreadcrumb(breadcrumb) {
            this.breadcrumb = breadcrumb
        }
    }
}
<template src="./AppBreadcrumbs.html"></template>
<script src="./AppBreadcrumbs.js" lang="babel"></script>
// Somewhere in your app/bootstrap file, add a centralised event hub/container

/* ============
 * Vue Event Hub
 * ============
 *
 * Distribute to components using global mixin
 *
 * http://taha-sh.com/blog/understanding-components-communication-in-vue-20
 */
const eventHub = new Vue();
Vue.mixin({
    data: function () {
        return {
            eventHub: eventHub
        }
    }
});