get all routes in a vue router

vue.jsVue Router

vue.js Problem Overview


Am trying to create a simple menu using vue router , id like to iterate all routes and display in my menu , currently am using below instance method in my component but i just get a function , how would i iterate to get individual routes ?

methods : {
 getMenuLinks: function() {
		
		var t = this.$router.map() ;
        //t returns a vue object instance
		return t._children ;
        // did not know how to iterate this 
   }

 }

I want to iterate all maped routes to get something like below of each mapped route :

<a v-link="{ path: 'home' }">Home</a>

vue.js Solutions


Solution 1 - vue.js

In Nuxt, the routes are generated automatically so I couldn't do what @zxzak suggested.

Here's what you can do in that case.

<template v-for="item in items">
	<b-nav-item :to="item.path">
		{{item.name}}
	</b-nav-item>
</template>

export default {
	created() {
		this.$router.options.routes.forEach(route => {
			this.items.push({
				name: route.name
				, path: route.path
			})
		})
	}
	, data() {
		return {
			items: []
		}
	}
}

Solution 2 - vue.js

You can simply iterate over $router.options.routes in your template:

<nav>
  <router-link v-for="route in $router.options.routes" :key="route.path" :to="route.path">{{ route.name }}</router-link>
</nav>

Maybe add styling for the selected route:

:class="{ active: route.path === $router.currentRoute.path }"

edit: for active class, use https://router.vuejs.org/api/#active-class instead

Solution 3 - vue.js

Instead of relaying on Vue's internals, put routes inside the data of your starting component.

var map = {
  '/foo': {
    component: Foo
  },
  '/bar': {
    component: Bar
  }
}

var routes = Object.keys(map)

var App = Vue.extend({
  data: function() {
    return {
      routes: routes
    }
  }
})

router.map(map)
router.start(App, '#app')

http://jsfiddle.net/xyu276sa/380/

Solution 4 - vue.js

Since vue-router 3.5, Router instance has now a getRoutes() method.
So an up to date answer could be

<router-link 
    for="r in routes" 
    :key="r.path" 
    :to="r.path"
>
    {{ r.name }}
</router-link>
computed: {
    routes() { return this.$router.getRoutes() }
}

Solution 5 - vue.js

Another solution is using Webpack's require.context

// search for src/pages/**/index.vue
function routesGen () {
  const pages = require.context('./pages/', true, /index\.vue$/)
  const filePaths = pages.keys()
  const getRoutePath = filePath => filePath.match(/\.(\/\S+)\/index\.vue/)[1]
  return filePaths.map(filePath => ({
    path: getRoutePath(filePath),
    component: pages(filePath).default
  }))
}

Solution 6 - vue.js

As VueRouter is simply a JavaScript class as other classes, you can extend it and add any custom functionality including the questionable one:

// TypeScript

import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';

class VueRouterEx extends VueRouter {
  matcher: any;

  public routes: RouteConfig[] = [];

  constructor(options) {
    super(options);
    const { addRoutes } = this.matcher;
    const { routes } = options;

    this.routes = routes;

    this.matcher.addRoutes = (newRoutes) => {
      this.routes.push(...newRoutes);
      addRoutes(newRoutes);
    };
  }
}

Vue.use(VueRouterEx);

const router = new VueRouterEx({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [],
});

export default router;

So, from any component, you can get the routes using this.$router.routes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimmy Obonyo AborView Question on Stackoverflow
Solution 1 - vue.jsRichard AyotteView Answer on Stackoverflow
Solution 2 - vue.jsphil294View Answer on Stackoverflow
Solution 3 - vue.jszxzakView Answer on Stackoverflow
Solution 4 - vue.jsjeanView Answer on Stackoverflow
Solution 5 - vue.jskenberkeleyView Answer on Stackoverflow
Solution 6 - vue.jsSerhii MatrunchykView Answer on Stackoverflow