Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue.

    <div id="nav">
      <!--Trying to create a dynamic nav-->
      <span v-for="route in routes" :key="route.to">
        <router-link :to="`${route.to}`">{{route.text}}</router-link> |
      </span>
    </div>
    <b-container>
      <router-view />
    </b-container>
  </div>

My goal is to update the 'routes' array as the user navigates through different views and components within views, reflecting the current location they are in. However, I understand that this approach is not typical in Vue as it would require a global variable of some sort. I am exploring the best way to handle updating a header nav when dealing with nested routes.

Sample routes:

  {
    path: '/Teams',
    name: 'Teams',
    component: Teams
  },
  {
    path: '/:teamName/Athletes',
    name: 'Athletes',
    component: Athletes
  },
  {
    path: '/:teamName/Athletes/:id',
    name: 'Athlete',
    component: Athlete
  }

I aim to include a route back to the Athletes page when on the Athlete page, dynamically displaying the selected ':teamName' on the header navigation in App.vue. This link should be adjustable based on the context.

User story example: /Teams -> Chooses team 'Team1' -> Redirected to /Team1/Atheltes -> selects an athlete -> redirected to /Team1/Athlete/1. How can I add a router-link in the header nav (currently in App.vue) to enable going back to /Team1/Athletes including the appropriate ':teamName'?

Answer №1

Using Vuex to manage your routes can streamline your workflow:

Store your routes in a state object:

// ...
state: {
  routes: [{
    path: '/Teams',
    name: 'Teams',
  }]
}

/Teams-> Remove any additional routes that may be added.

// ...
mutations: {
  deafultRoute(state, payload) {
    state.routes = state.routes.slice(0, 1); // Keep only 1 route
  }
}

/Team1/Atheltes -> Include the team route for the team:

// ...
mutations: {
  addTeamRoute (state, payload) {
    state.routes = state.routes.slice(0, 2); // Keep only 2 routes
    let newPath = {
      path: `/${payloadteamName}/Athletes`,
      name: 'Athletes'
    }
    state.routes[1] = newPath 
  }
}

/Team1/Athlete/1. -> Add the athlete route for the team:

// ...
mutations: {
  addAthleteRoute (state, payload) {
    state.routes = state.routes.slice(0, 3); 
    let newPath = {
      path: `/${payload.teamName}/Athletes/${payload.id}`,
      name: 'Athlete'
    }
    state.routes[2] = newPath 
  }
}

You probably don't need to store Components in the routes array.

Answer №2

Here's an example of how I approach it:

{
    path: '/Projects',
    name: 'Projects',
    component: Projects,
    meta: {
      module:'Projects'
    }
  }

By using the meta property, you can easily navigate back or perform other actions.

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

Sending an array as a query string

I am trying to send an array to my server using jsonp. Here is an example of the JSON I want to pass: ["something","another_thing",4,{"iam" : "anobject"}] However, I am unsure about how to actually pass an array. I thought it might work like this: some ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Employing API Integration with Node.js and AngularJS

Currently in the process of developing a language translating messaging application using Node and Angular. I have decided to utilize the Yandex API since Google Translate is not free. You can find more information about the API at www.yandex.com I am unc ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Obtaining the URL of the Parent Page Using Javascript

I encountered a situation in which, when I open a modal window dialog from Page1.aspx, if a user attempts to directly open that dialog by copying the URL and pasting it into the browser, I want to prevent the modal window from opening. It should only open ...

What could be causing my Bootstrap carousel to only slide once?

I'm currently working on integrating a Bootstrap Carousel into my website, but I've encountered an issue where it moves only once and then becomes unresponsive. After checking the file order, I couldn't find any issues there. So, I'm qu ...

JavaScript encoding and decoding challenges

Can anyone help me figure out what's wrong? I'm trying to encode and decode a simple input, but it just doesn't seem to work! Any ideas why? Thanks in advance for your assistance :) ENCODE: function encryption_encode(s, delta) { var te ...

Tips for assigning custom values using CSS and jQuery for a standalone look

I am facing a challenge with my HTML markup: <div> <figure></figure> <figure></figure> <figure></figure> </div> Alongside some CSS styling: div { position: relative; } figure { position: absolu ...

JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization: $scope.rawUsers = angular.copy($scope.users); Subsequently, I make modifications to the data like so: function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scop ...

I desire to alter the description of an item within a separate div, specifically in a bootstrap

I used the map method to render all the images. However, I need a way to track the current image index so that I can change the item description located in another div. Alternatively, if you have any other solutions, please let me know. App.js : import Ca ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Incorporating a sidemenu into a DOM using Ionic2 and Angular2 Typescript

I am currently struggling to properly integrate the sidemenu from the app.ts file. app.html: <ion-menu [content]="content"></ion-menu> <ion-nav id="nav" [root]="rootPage" #content ></ion-nav> app.ts import {App, IonicApp,Page, ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...

Encountered an issue while installing npm dependencies for webtorrent: "Error: Unable to locate 'fs' - Fountain-Js (Yeoman)"

Having trouble installing an NPM dependency in my code. Successfully installed the module using this command: npm install --save webtorrent This is the content of my package.json file: ./package.json { "dependencies": { "angular": "^1.5.0" ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

What is the best way to retrieve and display a detailed JSON object within views using Node.js?

Below is a snippet of code that deals with JSON arrays and how to handle them in a server setting. When sending data from the server, the code constructs a URL based on certain parameters and makes a request. If successful, it then logs the response and e ...