Sunday, 17 January 2021

Dynamic component selector for all routes in Vue

I would like to set up dynamic routing in Vue, driven by my backend API. The boilerplate that I've looked at suggests using a single component for all routes. A global navigation guard loads the current page data from the API and shows the correct page based on the component name sent from backend:

router.ts

const router = new VueRouter({
  routes: [
    {
      path: '*',
      component: PageSelector
    }
  ],
  mode: 'history'
})

router.beforeEach((to, from, next) => {
  loadModelByUrl(to.fullPath) // load async page data from API
  next()
})

PageSelector.vue

<template>
  <component v-if="model" :is="model.componentName" :key="model.guid"/>
</template>

App.vue

<template>
  <div id="app">
    <div id="nav"></div>
    <router-view />
  </div>
</template>

Are there any obvious downsides using this approach compared to using a more standard route config?



from Dynamic component selector for all routes in Vue

No comments:

Post a Comment