Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to use or if there are built-in Vue features that could assist me. Currently, I'm utilizing Vue3 and pinia.

Below is my current draft for the Breadcrumb component:

Breadcrumb.vue

<template>
    <div id="breadcrumb">
        <ul class="breadcrumb-wrapper">
            <li v-for="(breadcrumb, index) in breadcrumbList" :key="index" @click="navigate(index)"
                :class="{ 'linked': !!breadcrumb.link }">
                {{ breadcrumb.name }}
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'Breadcrumb',
    data() {
        return {
            breadcrumbList: []
        }
    },
    mounted() { this.updateList() },
    watch: { '$route'() { this.updateList() } },
    methods: {
        navigate(route) {
            if (this.breadcrumbList[route].link) this.$router.push(this.breadcrumbList[route].link)
        },
        updateList() { this.breadcrumbList = this.$route.meta.breadcrumb }
    }
}
</script>

I customize router entries like:

router.js

{
  path: "/building/:slug-:id",
  name: "building-detail",
  component: BuildingDetail,
  meta: {
    breadcrumb: [
      { name: 'buildings', link: 'buildings' },
      { name: 'campus-detail', link: 'campus-detail' },
      { name: 'buildings-detail' }
    ]
  }
},

I'm looking for a more efficient way to dynamically update names and links based on different pages. While my current approach may function, it feels incomplete and cumbersome. Is there a simpler method where I can store necessary data and URLs to pass them seamlessly between pages? Any insights from those who have tackled a similar challenge would be greatly appreciated.

Answer №1

Here is an example of how your Breadcrumb.vue file could be structured:

<template>
  <nav class="breadcrumb">
    <ul>
      <li v-for="(crumb, index) in breadcrumbs" :key="index">
        <router-link :to="crumb.to">{{ crumb.label }}</router-link>
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  computed: {
    breadcrumbs() {
      const route = this.$route;
      const matchedRoutes = route.matched;

      return matchedRoutes.map((routeItem) => ({
        label: routeItem.meta.breadcrumb || routeItem.name,
        to: this.getRoutePath(route, routeItem),
      }));
    },
  },
  methods: {
    getRoutePath(route, routeItem) {
      const matchedSegments = route.matched.slice(0, route.matched.indexOf(routeItem) + 1);
      return matchedSegments.map((segment) => segment.path).join('/');
    },
  },
};
</script>

<style scoped>
/* Customize your breadcrumb styling here */
</style>

And for your Router.js Object, it might look something like:

      {
        path: '/',
        name: 'Home',
        component: Home,
        meta: {
          breadcrumb: 'My Home', // Custom label for the breadcrumb
        },
      },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

How can I showcase the selected file using jQuery's querySelector?

I have successfully implemented a file upload feature using jQuery querySelector. Now, I am looking for a way to display the selected file name in a span element after the user selects the file. Here is my HTML code: <span id="filename"></span&g ...

The elements within the Popup Modal are not displaying as expected

I found a helpful tutorial that teaches how to display a Popup Modal Window when the page loads. However, I'm facing an issue where the modal is not showing the contents and images properly. The code I am working on can be found at jsFiddle. My goal ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

comparison of declarative loop and imperative loop

In my journey to transition from an imperative programming style to a declarative one, I've encountered a challenge related to performance when dealing with loops. Specifically, I have a set of original DATA that I need to manipulate in order to achie ...

Should we consider packaging the npm dependencies code along with our code as a best practice?

What is the best way to handle npm dependencies in our code bundle? If it's preferable to include the npm dependency code in our bundle, does it make sense to add it as a separate module or package? If not, how can I prevent bundling my dependencie ...

Vue: add a CSS class to products when they are in the shopping cart

As I delve into creating a shopping cart using laravel + vue, I am encountering a major obstacle related to vue's functionality. Within my cart component, the goal is to allow users to effortlessly add or remove products by simply clicking. When a pr ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

Navigating within components using code is an essential skill when working with Vue Router

I am currently developing a Quasar application powered by Vue 3 with vue-router version 4 All my routes are properly configured and function well when navigating from a component template using <router-link to="/route">Go to route</rout ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

I can't figure out why my SCSS isn't loading, even though I've added it to the webpack.mix.js file in my Laravel project that's set up with React.js

I'm facing a problem where my SCSS is not loading in the VideoBackground.js component of my Laravel project built with React.js, even though I have set it up correctly in the webpack.mix.js file. The file path for the videoBackground.scss file within ...

What are the steps to modify the placeholder of the formik <Field/> component?

Struggling to figure out how to make the date input empty with Formik. I just want it to display nothing initially, but have been unable to do so after hours of trying different methods. <Field name="date" type="date" className ...

Transferring session id across various devices using PHP

Here's the scenario: I have two users accessing different pages on separate devices - one user is on page 1 and the other is on page 2. My goal is to implement PHP forms on page 1 that can dynamically change the content displayed on the second user& ...

Evaluation of Library (VueJS) - Displaying various components in an individual test case

Just starting out with testing and have a simple question: I am working on testing a checkbox component. I understand the basics, but how can I render multiple components within one it block? Here is my current code. I am stuck on the second test where I ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

In my database, I have two tables: Table1 and Table2. To better illustrate my issue, I have included a picture for reference

https://i.stack.imgur.com/GQAMy.jpg I am facing a challenge with joining two tables, table1 and table2, in MySQL. I need assistance in creating the resultant table as shown in the attached picture. Your help in solving this issue would be greatly appreci ...

Sending data from an Ionic application to a server

I came across this solution on a forum, but it lacks detailed explanation for me to customize it according to my requirements. The author also mentions a stack overflow question, which led to various "different" solutions leaving me feeling confused. Belo ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Issues have arisen due to server calls being affected by AngularJS routing

I have implemented AngularJS in a nodewebkit application. There are three main views: Home.html Conversation.html Login.html Upon login, the following code is executed: $state.go('home.main'); which triggers the following state c ...