How can I dynamically set destination component in Vue router

I am trying to dynamically set the target component for a vue-router route.

The reason is because I need to get data from the server to find out the correct target.

One solution I was thinking about was adding global protection like:

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(() => {
    // set the "to" component, but how?
    next();
})

      

But as the comment says, how would I set the "component" - there is no component property in the "to" object. (It looks like it's in the .default.render components, but it's not documented and doesn't look like it should be running.)

Another alternative is to use the above logic, but add some custom redirection code, but then I found that there was no way to create a dynamic / new route targeting the correct component.

How should you create a route to a destination that is not known at build time?

+3


source to share


1 answer


This solution works.

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(component => {
    if (to.matched.length === 0) {
      // the target route doesn't exist yet
      router.addRoutes({path: to.path, component: component})
      next(to.fullPath)
      return
    } else {
      // the route and component are known and data is available
      next()
    }
})

      



The key was finding a link in my comment above that shows the vue-router command that implements addRoutes()

.

One thing to be aware of is that new routes are added at the end (makes sense), so any wildcards can create unintended matches. I had a generic route redirected to the default page. But it matched before the new added match, because it was previously a list. And it caused a stack overflow. In fact, the code after if (to.matched.length === 0)

is the default route.

+1


source







All Articles