How to make dynamic routes on the vue router?

I suppose getDetailMenu is calling API method to get listMenu.
You can create route dynamically using addRoutes method

Pseudo code

created() {
  this.getDetailMenu(this.$route.path)
    .then((listMenu) => {
      // you need to return listMenu from getDetailMenu
      listMenu.forEach((item, index) => createAndAppendRoute(item, index))
    })
},
methods: {
  createAndAppendRoute: (item, index) => {
    console.log(item, index)
    // Base on your data, you should be able to create router name and path from item and index
    // here is just an example
    let newRoute = {
      path: `/${item}`,
      name: `${item}_${index}`,
      components: { default: Application, header: MainNavbar },
    }

    this.$router.addRoutes([newRoute])
  }
}

Leave a Comment