Reputation: 1186
I would like to loop over my routes
using v-for
in order to generate the <router-link>
s dynamically in the template
section.
Currently I have no idea how to address the router
param, that is defined in main.js
, in the template
section of my jvds-navigation.vue
component.
Here are the scripts, I added comments, where my problem occurs:
main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
// Import the routes file
import { routes } from './router/routes.js'
// Router
Vue.use(VueRouter)
const router = new VueRouter({
routes,
base: __dirname,
mode: 'history'
})
new Vue({
router, // short for "router: router"
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<span id="app" class="o-root">
<jvds-navigation class="..."></jvds-navigation>
<router-view></router-view>
</span>
</template>
<script>
import JvdsNavigation from "@/components/layout/jvds-navigation.vue"
export default {
name: "App",
components: {
JvdsNavigation
}
};
</script>
jvds-navigation.vue
<template>
<div>
<div class="[...]">
<!--
`nav` should have a `v-for` over the routes imported
in main.js (example given, but wrong).
But how can I address routes here?
-->
<nav class="[...]" v-for="routeItem in routes">
<!-- These should be created dynamically... -->
<router-link to="/about">
<a>About</a>
</router-link>
<router-link to="/cv">
<a>CV</a>
</router-link>
<router-link to="/contact">
<a>Contact</a>
</router-link>
</nav>
</div>
</div>
<script>
// How do I get `routes` (imported in main.js) recognized by
// this component in order to be able to loop over it in the
// `template` section?
export default {
name: "jvds-navigation"
};
</script>
Thank you for any tips, tricks and hints!
Upvotes: 13
Views: 9803
Reputation: 3536
Use v-for
on router-link
.
I've used this.$router.options.routes
to get all routes. You can also pass it as prop to jvds-navigation
.
This is a small example of you how can do it:
example routes
const routes = [
{
path: '/',
component: Home,
name: 'Home',
},
{
path: '/about',
component: About,
name: 'About'
},
];
template
<nav>
<router-link v-for="route in routes" :key="route.path" :to="route.path">
{{route.name}}
</router-link>
</nav>
script
export default {
name: 'Navigation',
data() {
return {
routes: this.$router.options.routes
};
}
// or use computed
// computed: {
// routes() {
// return this.$router.options.routes;
// }
// }
}
Upvotes: 22