|
| 1 | +import {ComponentOptions, PluginObject, VueConstructor} from 'vue' |
| 2 | +import { Route } from 'vue-router'; |
| 3 | + |
| 4 | +type CallbackFunction = () => string; |
| 5 | + |
| 6 | +class VueBreadcrumbs implements PluginObject<ComponentOptions<Vue>> { |
| 7 | + install(Vue: VueConstructor<Vue>, options = {}) { |
| 8 | + |
| 9 | + Object.defineProperties(Vue.prototype, { |
| 10 | + $breadcrumbs: { |
| 11 | + get(): Route[] { |
| 12 | + return this.$route.matched.map((route: Route) => ({ |
| 13 | + ...route, |
| 14 | + path: route.path.length > 0 ? route.path : '/' |
| 15 | + })); |
| 16 | + } |
| 17 | + } |
| 18 | + }); |
| 19 | + |
| 20 | + Vue.component('Breadcrumbs', Vue.extend({ |
| 21 | + methods: { |
| 22 | + getBreadcrumb(bc: string | CallbackFunction): string { |
| 23 | + return typeof bc === 'function' ? bc.call(this, this.$route.params) : bc; |
| 24 | + }, |
| 25 | + getPath(crumb: Route): string { |
| 26 | + let {path} = crumb; |
| 27 | + |
| 28 | + for (const [key, value] of Object.entries(this.$route.params)) { |
| 29 | + path = path.replace(`:${key}`, value); |
| 30 | + } |
| 31 | + |
| 32 | + return path; |
| 33 | + } |
| 34 | + }, |
| 35 | + template: ` |
| 36 | + <ol |
| 37 | + class="breadcrumb" |
| 38 | + v-if="$breadcrumbs.length" |
| 39 | + > |
| 40 | + <li |
| 41 | + class="breadcrumb-item" |
| 42 | + v-if="crumb.meta.breadcrumb" |
| 43 | + v-for="(crumb, i) in $breadcrumbs" |
| 44 | + :key="i" |
| 45 | + > |
| 46 | + <router-link |
| 47 | + active-class="active" |
| 48 | + :to="{ path: getPath(crumb) }" |
| 49 | + :tag="i != $breadcrumbs.length - 1 ? 'a' : 'span'" |
| 50 | + > |
| 51 | + {{ getBreadcrumb(crumb.meta.breadcrumb) }} |
| 52 | + </router-link> |
| 53 | + </li> |
| 54 | + </ol>`, |
| 55 | + ...options |
| 56 | + })) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +export default new VueBreadcrumbs(); |
0 commit comments