How to use vue2 to encapsulate breadcrumb components

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 routesarray 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 routesprops attribute called to receive routing information. In the component's template, we use v-forthe directive to iterate over routesthe array and generate the corresponding breadcrumbs. We used router-linkthe 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.vueuse 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.vueuse computedthe prop in the component to calculate the current page position. We first define an empty array routes, then use whilea loop to traverse the current route and its parent route, and add them to routesthe array in turn. Finally, we routespass 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.

Guess you like

Origin blog.csdn.net/m0_70718568/article/details/130337747