Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all routes in a vue router

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> 
like image 988
Jimmy Obonyo Abor Avatar asked Mar 20 '16 23:03

Jimmy Obonyo Abor


People also ask

How do I get the current route on my Vue router?

We can use this. $router. currentRoute. path property in a vue router component to get the current path.

How do I get parameters on my Vue router?

In the composition API, we use the useRoute hook. to get the value of the id route parameter with this. $route.params.id with the options API. We call useRoute to return the route object and then we get the value of the id route parameter with route.params.id .

How do I watch my Vue route?

To listen for route change events with Vue. js and Vue Router, we can watch the $route object in our component. to watch the $route in our component. We set deep to true to watch for all changes in the $route object's contents.

What is router View />?

Router-view vue file. It's basically the view where the components are rendered. It's like the main div that contains all the components, and it returns the component that match the current route.


2 Answers

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: []         }     } } 
like image 150
Richard Ayotte Avatar answered Oct 03 '22 09:10

Richard Ayotte


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

like image 20
phil294 Avatar answered Oct 03 '22 09:10

phil294