As a newcomer to vuejs, I am using vue cli 3 for my project which consists of various components. One of the components is a menu component where I retrieve all the menu items from an API (code provided below). I have integrated vue-router for routing purposes, but I am facing difficulty in populating the routes array inside the router object. Despite searching extensively, I couldn't find a solution.
Instead of manually defining paths and components in the routes array, I want it to be dynamically populated with the items fetched 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 file looks like this:
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
})
Here is the JSON structure received 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.