frandiox / vite-ssr

Use Vite for server side rendering in Node
MIT License
823 stars 91 forks source link

Unable to request data to set header title in hook function 'onServerPrefetch', page has already completed rendering before await #206

Closed lita-jerry closed 1 year ago

lita-jerry commented 1 year ago
const sleep = function (delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        resolve(1)
      } catch (e) {
        reject(0)
      }
    }, delay)
  })
}

// SSR
onServerPrefetch(async () => {
  await sleep(100) // Simulate request data
  try {
      useHead({
          title: 'Display the results after the request',
        })
  }
  catch (error) {
    console.error(error)
    console.error(6666666666666)
  }
})

No expected output header, error message as follows

[Vue warn]: inject() can only be used inside setup() or functional components.
Error: You may forget to apply app.use(head)
    at injectHead (/node_modules/.pnpm/@vueuse+head@0.7.6_vue@3.2.37/node_modules/@vueuse/head/dist/index.js:118:11)
    at Proxy.useHead (/node_modules/.pnpm/@vueuse+head@0.7.6_vue@3.2.37/node_modules/@vueuse/head/dist/index.js:300:16)
    at eval (/src/pages/user/[uid].vue:282:32)
6666666666666

But I have already completed the setting of app. use (head) in main.js. How can I dynamically set the title after requesting data?

lita-jerry commented 1 year ago

If the head is not set in the 'onServerPrefetch' function, the head will display normally, but the page cannot execute the onMount function as if it is blocked by something