vuejs / router

🚦 The official router for Vue.js

Home Page:https://router.vuejs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Param Resolver before Router isReady

valoricDe opened this issue · comments

What problem is this solving

Before we mount our Vue App we want to do some actions (load api response to know which theme to render).
For this it would be very helpful if we could resolve the params given in the URL before the routers isReady promise resolved.

Previously in vue router 3 it was simple:

  const router = setupOurRouter();
  router.replace(urlPath); // this will set country and lang for our app
  const { params = {} } = router.currentRoute;
  setTheme(params);

Now we have to (see describe alternatives I have considered section)

Proposed solution

Cool would be a function we can pass the routes and the path and it would resolve the params synchroniously.

Describe alternatives you've considered

Now we need the roundtrip through the isReady:

const path = window.location.hash.substring(1);
const history = widgetMode ? createMemoryHistory() : createWebHashHistory();
history.replace(path);
const router = createRouter({ history, ... });
router.isReady().then(() => {
  const params = router.currentRoute.value.params;
  ...
});

or push

const path = window.location.hash.substring(1);
const history = widgetMode ? createMemoryHistory() : createWebHashHistory();
const router = createRouter({ history, ... });
router.push(path).then(() => {
  const params = router.currentRoute.value.params;
  ...
});

The usage of isReady is needed even in Vue router 3 to account for async navigations. Using other methods like router.resolve (sync) could help your use case but it o it works if you have no navigation guards that can redirect

Hi thanks for getting back so quickly. As I see from example router.resolve requires me to pass something like router.resolve({ name: 'LandingPage', params: { country: 'DE', language: 'de' }}) but what I need is router.resolveMyRoute('/DE/de') -> { params: { country: 'DE' ...} } so the other way around.

When I try router.resolve with a string router.resolve('/DE/de') it returns { location: undefined, route: undefined, href: '#/DE/de' }

I need this because I want to do something like:

const router = setupRouter(window.location.hash.substring(1));
const params = router.currentRoute.value.params;

if (params.themeId === 'myTheme') {
    loadTheme(params.themeId)
      .then(() => app.mount('#app') )
  } else {
  app.mount('#app')
  }

FYI router.resolve('/...') also works 😄

Ah damn. I kept on getting on the vue router 3 docu for the router.resolve and expected { location, router, href } as response. But it returns now directly the route object. So I can read the params directly from the object. Sorry for wasting your time. And thanks for the pointer again to router.resolve (https://router.vuejs.org/api/interfaces/Router.html#resolve)