2022-09-10 13:57:16 +00:00
|
|
|
import { defineNuxtPlugin, loadPayload, addRouteMiddleware, isPrerendered } from '#app'
|
|
|
|
|
|
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
|
|
// Only enable behavior if initial page is prerendered
|
2022-09-14 13:01:02 +00:00
|
|
|
// TOOD: Support hybrid and dev
|
2022-09-10 13:57:16 +00:00
|
|
|
if (!isPrerendered()) {
|
|
|
|
return
|
|
|
|
}
|
2022-09-13 20:20:23 +00:00
|
|
|
const prefetchPayload = async (url: string) => {
|
2022-09-10 13:57:16 +00:00
|
|
|
const payload = await loadPayload(url)
|
2022-09-13 20:20:23 +00:00
|
|
|
if (!payload) { return }
|
2022-09-10 13:57:16 +00:00
|
|
|
Object.assign(nuxtApp.payload.data, payload.data)
|
|
|
|
Object.assign(nuxtApp.payload.state, payload.state)
|
2022-09-13 20:20:23 +00:00
|
|
|
}
|
|
|
|
nuxtApp.hooks.hook('link:prefetch', async (to) => {
|
|
|
|
await prefetchPayload(to)
|
|
|
|
})
|
|
|
|
addRouteMiddleware(async (to, from) => {
|
|
|
|
if (to.path === from.path) { return }
|
|
|
|
await prefetchPayload(to.path)
|
2022-09-10 13:57:16 +00:00
|
|
|
})
|
|
|
|
})
|