Get all routes in vue router

I am trying to create a simple menu using vue router, I like to iterate over all the routes and display in my menu, I currently use the instance method below in my component, but I just get a function, how would I iterate over 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 over all displayed routes to get something like below each displayed route:

 <a v-link="{ path: 'home' }">Home</a> 
+28
vue-router
source share
4 answers

In Nuxt, routes are generated automatically, so I could not do what @zxzak suggested.

Here is what you can do in this 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: [] } } } 
+32
source share

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

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

Perhaps we’ll add styles for the selected route:

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

change: for the active class use https://router.vuejs.org/api/#active-class instead

+7
source share

Instead of relaying to Vue's internal components, place the routes inside the data of your source 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/

+5
source share

Another solution is to use Webpack 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 })) } 
0
source share

All Articles