nuxt: Allow layouts or the error layout to use fetch/asyncData
What problem does this feature solve?
My error page lives in a layout that needs to pull data for menus/footer, since layouts can’t have fetch/asyncData blocks I normally add the fetch logic to the pages that use a specific layout. However this workaround doesn’t work for the error page since it is not a page, but a layout.
This can’t be done on NuxtServerInit because:
a) requests dispatched in nuxtServerInit are blocking, i.e. nuxt waits until the promise returned from nuxtServerInit is resolved before continuing, which makes things x2 slower when a page has other requests to make (all requests can and should be run in parallel) b) different layouts have different fetch needs c) wouldn’t work on SPA mode
Do you guys have any workaround for this? Currently, my 404 error pages render with an empty footer and menu.
What does the proposed changes look like?
Add fetch and/or asyncData support to layouts, or at least the error layout.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 77
- Comments: 22 (5 by maintainers)
This is still a problem in v2
Does anyone have a solution for this? I’m trying to get the item count for a shopping cart to put in my navbar.
@luishdz1010 - Word is on the street that with @pi0 's latest merges the next version of Nuxt should allow fetch() on layout (and hopefully should be resolved with the page fetch in async)
For everyone who is stuck with that issue, you can use
serverPrefetchofVue.js. Since Layout is a Vue component it will work. Check documentation here https://ssr.vuejs.org/guide/data.html#logic-collocation-with-componentsI use anonymous middle to fetch data in layout on SPA mode, it worked for me. https://nuxtjs.org/api/pages-middleware#anonymous-middleware
Is there any example to see the code for this?
Hi, I solved my problem this way: