This repository was archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(nuxt): prefetch middleware/layouts + await layout loading (#10155)
- Loading branch information
Showing
3 changed files
with
45 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
packages/nuxt/src/pages/runtime/plugins/prefetch.client.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { hasProtocol } from 'ufo' | ||
import { defineNuxtPlugin, useNuxtApp, useRouter } from '#app' | ||
// @ts-ignore | ||
import layouts from '#build/layouts' | ||
// @ts-ignore | ||
import { namedMiddleware } from '#build/middleware' | ||
|
||
export default defineNuxtPlugin(() => { | ||
const nuxtApp = useNuxtApp() | ||
const router = useRouter() | ||
|
||
// Force layout prefetch on route changes | ||
nuxtApp.hooks.hook('app:mounted', () => { | ||
router.beforeEach(async (to) => { | ||
const layout = to?.meta?.layout | ||
if (layout && typeof layouts[layout] === 'function') { | ||
await layouts[layout]() | ||
} | ||
}) | ||
}) | ||
// Prefetch layouts & middleware | ||
nuxtApp.hooks.hook('link:prefetch', (url) => { | ||
if (hasProtocol(url)) { return } | ||
const route = router.resolve(url) | ||
if (!route) { return } | ||
const layout = route?.meta?.layout | ||
let middleware = Array.isArray(route?.meta?.middleware) ? route?.meta?.middleware : [route?.meta?.middleware] | ||
middleware = middleware.filter(m => typeof m === 'string') | ||
|
||
for (const name of middleware) { | ||
if (typeof namedMiddleware[name] === 'function') { | ||
namedMiddleware[name]() | ||
} | ||
} | ||
|
||
if (layout && typeof layouts[layout] === 'function') { | ||
layouts[layout]() | ||
} | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters