get all routes in a vue router
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
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/
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() }
}