I am new to vuejs I work with vue cli 3. and I have a project with different components. I have a menu component, where I get all the menu items from an api(code bellow). I have installed vue-router, to do the routing, but my problem is that I dont know how to fill the routes array inside router object. I have searched a lot but nothing helped.
So basically instead of filling the routes with harcoded paths, and components.. I want to automatically fill it with the items I get from the api.
<template>
<div class="Menu">
<nav class="navbar navbar-default navbar-custom">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav navbar-right" v-for="menu in main_menu" v-bind:key="menu.menu_item">
<router-link class="dropdown-toggle" data-toggle="dropdown" :to="menu.menu_url"></router-link>
<li><router-link :to="menu.menu_url">{{ menu.menu_item }}</router-link>
<ul class="dropdown-menu" v-for="list in menu.list_item" v-bind:key="list.url">
<li><router-link v-bind:to="list.menu_url">{{ list.title }}</router-link></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<router-view></router-view>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Menu',
data () {
return {
main_menu: null,
error:""
}
},
mounted () {
//console.log(this.page);
axios({ method: "GET", "url": "http://apiurl" }).then(result => {
this.main_menu = result.data.main_menu;
},
error => {
this.error = error;
});
}
}
}
</script>
the router.js is:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
var route = [
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/awards',
name: 'Awards',
component: () => import('./views/Awards.vue')
},
{
path: '/news',
name: 'News',
component: () => import('./views/News.vue')
},
{
path: '/product',
name: 'Product',
component: () => import( './views/Product.vue')
},
{
path: '/page',
name: 'Page',
component: () => import('./views/Page.vue')
}
];
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: route
})
And the json I get from the api :
main_menu: [
{
menu_item: "Home",
menu_url: "/home",
list_item: [ ]
},
{
menu_item: "Awards",
menu_url: "/awards",
list_item: [ ]
},
{
menu_item: "Product",
menu_url: "product",
list_item: [
{
url: "/product/sticker",
title: "sticker"
},
{
url: "/product/cup",
title: "Promotion Cup"
}
]
},
{
menu_item: "News",
menu_url: "/news",
list_item: [ ]
},
{
menu_item: "Page",
menu_url: "/page",
list_item: [ ]
}
]
Thank you.