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>
We can use this. $router. currentRoute. path property in a vue router component to get the current path.
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 .
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.
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.
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: [] } } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With