Vue2 package breadcrumb component
Breadcrumbs are a common navigation component, usually used to display the location of the current page, allowing users to know their location at any time. This article will introduce how to use Vue2 to wrap a breadcrumb component.
1. Create the breadcrumb component
We first need to create a Vue component to implement the breadcrumbs functionality. In this component, we need to receive an routes
array as a parameter, and then generate breadcrumbs based on routing information.
vue
Copy
<template>
<div class="breadcrumb">
<ul>
<li v-for="(route, index) in routes" :key="route.path">
<router-link :to="route.path">{
{ route.meta.title }}</router-link>
<span v-if="index !== routes.length - 1">/</span>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Breadcrumb',
props: {
routes: {
type: Array,
required: true,
default: () => []
}
}
}
</script>
In this component, we use a routes
props attribute called to receive routing information. In the component's template, we use v-for
the directive to iterate over routes
the array and generate the corresponding breadcrumbs. We used router-link
the component to implement routing jumps, and added a slash separator between each breadcrumb.
2. Use the breadcrumb component
After creating the breadcrumb component, we can use it in other components. For example, we can App.vue
use the breadcrumb component in the component to show where the current page is located.
vue
Copy
<template>
<div>
<breadcrumb :routes="routes"></breadcrumb>
<router-view></router-view>
</div>
</template>
<script>
import Breadcrumb from './Breadcrumb.vue'
export default {
name: 'App',
components: {
Breadcrumb
},
computed: {
routes() {
const routes = []
let route = this.$route
while (route) {
routes.unshift(route)
route = route.parent
}
return routes
}
}
}
</script>
In this example, we App.vue
use computed
the prop in the component to calculate the current page position. We first define an empty array routes
, then use while
a loop to traverse the current route and its parent route, and add them to routes
the array in turn. Finally, we routes
pass this array as props to the breadcrumbs component to generate the corresponding breadcrumbs.
3. Summary
In this article, we introduced how to use Vue2 to wrap a breadcrumb component. Through this component, we can easily generate various complex breadcrumbs to let users know their location at any time. At the same time, developing with Vue2 allows us to build applications more efficiently.