How to keep your vue-router up-to-date

As a newcomer to vuejs, I am using vue cli 3 for my project which consists of various components. One of the components is a menu component where I retrieve all the menu items from an API (code provided below). I have integrated vue-router for routing purposes, but I am facing difficulty in populating the routes array inside the router object. Despite searching extensively, I couldn't find a solution.

Instead of manually defining paths and components in the routes array, I want it to be dynamically populated with the items fetched from the API.

<template>
  <div class="Menu">
    <nav class="navbar navbar-default navbar-custom">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
        </div>
        <div class="collapse navbar-collapse" id="navbar-collapse-1">
          <ul class="nav navbar-nav navbar-right" v-for="menu in main_menu" v-bind:key="menu.menu_item">

            <router-link class="dropdown-toggle" data-toggle="dropdown" :to="menu.menu_url"></router-link>
            <li><router-link :to="menu.menu_url">{{ menu.menu_item }}</router-link>
              <ul class="dropdown-menu" v-for="list in menu.list_item" v-bind:key="list.url">
                <li><router-link v-bind:to="list.menu_url">{{ list.title }}</router-link></li>
              </ul>
            </li>

          </ul>

        </div>
        
      </div>
    </nav>
    <router-view></router-view>

  </div>
</template>

<script>
  import axios from 'axios';

  export default {
  name: 'Menu',
  data () {
    return {
      main_menu: null,
      error:""
    }
  },
  mounted () {
    //console.log(this.page);
    axios({ method: "GET", "url": "http://apiurl" }).then(result => {
      this.main_menu = result.data.main_menu;
    },
    error => {
      this.error = error;
    });
  }
  }
}
</script>

The router.js file looks like this:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

var route = [
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/awards',
    name: 'Awards',
    component: () => import('./views/Awards.vue')
  },
  {
    path: '/news',
    name: 'News',
    component: () => import('./views/News.vue')
  },
  {
    path: '/product',
    name: 'Product',
    component: () => import( './views/Product.vue')
  },
  {
    path: '/page',
    name: 'Page',
    component: () => import('./views/Page.vue')
  }
];

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: route
})

Here is the JSON structure received from the API:

main_menu: [
    {
      menu_item: "Home",
      menu_url: "/home",
      list_item: [ ]
    },
    {
      menu_item: "Awards",
      menu_url: "/awards",
      list_item: [ ]
    },
    {
      menu_item: "Product",
      menu_url: "product",
      list_item: [
        {
          url: "/product/sticker",
          title: "sticker"
        },
        {
          url: "/product/cup",
          title: "Promotion Cup"
        }
      ]
    },
    {
      menu_item: "News",
      menu_url: "/news",
      list_item: [ ]
    },
    {
      menu_item: "Page",
      menu_url: "/page",
      list_item: [ ]
    }
  ]

Thank you.

Answer №1

To integrate vue router into your project, you have the option to include it during the initial setup or add it later on. After importing vue router, the next step is to define your routes within the application. For detailed instructions on how to set up routes, refer to this resource - https://scotch.io/tutorials/getting-started-with-vue-router.

If you choose to include the router option during the project creation process, a significant portion of the configuration work will be automatically handled by the cli tool.

Answer №2

I recently took this path

let journey = [
  {
    route: '/*',
    destination: 'all',
    componentLoad: () => import('./component/All.vue')
  }
];

Answer №3

To dynamically append routes to an existing router, you can utilize the router.addRoutes([]) method like so:

router.js :

Vue.use(Router)

// define your static routes
var route = [
  {
    path: '/home',
    name: 'Home',
    component: Home
  }
];

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: route
})

anywhere else

import router from '@/router'

router.addRoutes([{
    path: '/awards',
    name: 'Awards',
    component: () => import('./views/Awards.vue')
  },
  {
    path: '/news',
    name: 'News',
    component: () => import('./views/News.vue')
  },
  {
    path: '/product',
    name: 'Product',
    component: () => import( './views/Product.vue')
  },
  {
    path: '/page',
    name: 'Page',
    component: () => import('./views/Page.vue')
  }
])
router.push('/page')

UPDATE: another example with promise

import router from '@/router'

const getRoutesFromApi = () => {
  return new Promise((resolve, reject) => {
    const data = [
      {
        path: '/awards',
        name: 'Awards',
        component: () => import('./views/Awards.vue')
      },
      {
        path: '/news',
        name: 'News',
        component: () => import('./views/News.vue')
      },
      {
        path: '/product',
        name: 'Product',
        component: () => import( './views/Product.vue')
      },
      {
        path: '/page',
        name: 'Page',
        component: () => import('./views/Page.vue')
      }
    ]
    setTimeout(resolve(data), 5000)
  })
}

getRoutesFromApi().then(response => router.addRoutes(response))

UPDATE 2 : more concrete example

import router from '@/router'
import axios from 'axios'

axios.get('http://your-api/whatever').then(response => {
    // response contains your data as json, you have to fetch them to get vuejs route-like object
    const routes = JSON.parse(response.data).map(o => {
        // here you have to transform your data in vuejs route item for example
        return {
            path: o.menu_url
            name: o.menu_item + 'View'
            component: () => import('./views/' + o.menu_item + '.vue')
        }
    })
    router.addRoutes(routes)
}

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

Updating row color according to values obtained from the map function in ReactJs

I have been experimenting with various methods to change the color of table rows based on specific values within a map function. Despite trying solutions like the UseRef hook and browsing through stack overflow, I have yet to achieve success. {dat ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

Sending messages on Discord.js at one-minute intervals

Hey there, I'm currently facing an issue while trying to automate a message sending process on Discord. The specific error that keeps popping up is: bot.sendMessage is not a function I'm puzzled as to why this error occurs, so I've include ...

Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success. Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of re ...

Unexpectedly, the Discord bot abruptly disconnects without any apparent cause

Hey there! I've encountered an issue with my Discord bot - it keeps disconnecting after a few hours without any apparent cause! This particular bot is designed to regularly ping the Apex Legends game servers to check their status and display the ser ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

The code snippet $(this).nextAll("#...").eq(0).text("***") isn't functioning as expected

I am experiencing an issue with the following line of code: $(this).nextAll("#status").eq(0).text("Deleted"). I am trying to insert the text "Deleted" in a <span> tag, but it does not seem to be working... Here is my code: admin.php PHP: $sql = "SE ...

Issue with EaselJS: mouse events are no longer functional

I'm currently working on adding a touch animation using the EaselJs library. Interestingly, when I load an image from a local folder, all mouse events work as expected, such as onPress. However, things take a different turn when I opt to use an imag ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Ways to eliminate dates from the text of listed items

Before finalizing their registration, users on our site are shown a review page. This panel displays all the items they have selected, creating a unique and variable list for each individual. However, each item in the list starts with a distracting date/ti ...

An easy way to create an input field after clicking a button

When I try to add a field on Button Click, the default field is not showing and does not get added upon button click I have put in my best effort but I cannot figure out what the problem is. I have added functions and used Math to generate a unique id. Th ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Error: Unable to locate module: 'fs' in Next.js

import nookies from 'nookies'; import { firebaseAdmin } from "../firebaseAdmin"; import { TChildren } from "../types/app/app.types"; interface Props { children: TChildren; } export default function ProtectedRoute(props ...

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

"Implementing an AngularJS factory that returns a State object instead of typical JSON data fetched from

I have created two factories and I am calling the first one from the second one in my controller. However, instead of receiving JSON data, I am getting data as $$State. I am new to AngularJS and have tried multiple solutions but have not been able to resol ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

How can I implement conditional rendering with React on a div element?

Is it possible to implement conditional rendering by simply adding the boolean checked isVisible=true onto the div? Will this ensure that it only renders when true? Could there be any potential issues with the component's state changing after renderi ...