0
votes

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.

3

3 Answers

0
votes

You need to import vue router. You can choose to import vue router when creating a new project or later by adding vue router to the project.

Once you do that you need to define your routes. Please follow this link - https://scotch.io/tutorials/getting-started-with-vue-router.

Basically if you include router option while creating new project most of work is done for you by cli.

0
votes

Well I just used this route

var route = [
  {
    path: '/*',
    name: 'all',
    component: () => import('./component/All.vue')
  }
];
0
votes

To dynamically add route to existing router, you could use router.addRoutes([]) as follow :

router.js :

Vue.use(Router)

// define your static routes
var route = [
  {
    path: '/home',
    name: 'Home',
    component: Home
  }
];

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: route
})

anywhere else

import router from '@/router'

router.addRoutes([{
    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')
  }
])
router.push('/page')

UPDATE: another example with promise

import router from '@/router'

const getRoutesFromApi = () => {
  return new Promise((resolve, reject) => {
    const data = [
      {
        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')
      }
    ]
    setTimeout(resolve(data), 5000)
  })
}

getRoutesFromApi().then(response => router.addRoutes(response))

UPDATE 2 : more concrete example

import router from '@/router'
import axios from 'axios'

axios.get('http://your-api/whatever').then(response => {
    // response contains your data as json, you have to fetch them to get vuejs route-like object
    const routes = JSON.parse(response.data).map(o => {
        // here you have to transform your data in vuejs route item for example
        return {
            path: o.menu_url
            name: o.menu_item + 'View'
            component: () => import('./views/' + o.menu_item + '.vue')
        }
    })
    router.addRoutes(routes)
}