Home  >  Q&A  >  body text

Best way to preload route data before accessing the route.

Before rendering the page for a given route, I want to first get the necessary data synchronously. Ideally I'd like to get the data in the page component, but I'm not opposed to doing it in the router file. I've read and tried various approaches, but part of the challenge comes from the fact that there are multiple ways to build components, and the use of certain features varies.

In my case I use Composition API and

P粉197639753P粉197639753307 days ago1006

reply all(2)I'll reply

  • P粉546257913

    P粉5462579132023-11-18 12:39:56

    First of all, beforeRouteUpdate is only triggered when the actual route is updated, but does not go to another component/page like the official tells here.

    An example of what might trigger a lifecycle hook is

    <button @click="$router.push({ hash: `#${Math.floor(Math.random() * 10)}` })">
      random hash
    </button>
    

    onBeforeRouteLeave Works perfectly, as you would expect, when moving from one page to another.

    For the original question, you could implement some kind of router middleware like Nuxt does . This way you wait for the HTTP call and only then allow actual navigation. So it's almost possible to create a block navigation effect.

    I'm not sure how to write it using the Composition API, but I know it works perfectly with the Options API (there are plenty of blog posts available). setup itself runs in it's own life cycle way and I imagine a lot of things are pretty tricky.

    TLDR: In my opinion, a good router middleware page wrapper (like layout) is the perfect combination in your case. There you can set up an observer for quite a few pages at the same time.

    But everything depends on how you want to organize yourself and structure your code.


    The skeleton screen gives a faster feel than blocking, but in general you can also use prefetch< /a> (also shipped with Nuxt by default) to get some hints and maybe Certain resources are required before loading them. (Other tricks in the same domain to speed up your network requests)

    reply
    0
  • P粉545956597

    P粉5459565972023-11-18 11:49:37

    There is a solution - use top level await - https://vuejs.org/api/sfc-script-setup.html#top-level-await

    Just wrap the RouterView component in a Suspense component as shown below - https://vuejs.org/guide/built-ins/suspense.html#combining-with-other-components( Don't use unnecessary components)

    The only thing to note is that the "loading screen" will be visible on the initial request.

    I made a small demo for you so you can try it out - https://github.com/ileue/vue-top-level-await-demo

    reply
    0
  • Cancelreply