Rewrite the title as: How to pass data from Node.js using SSR in Vue 3
P粉078945182
P粉078945182 2023-08-25 18:42:30
0
1
606
<p>I'm building a website using vue.js 3 and I want to use server-side rendering. I also want to be able to pass data from my fastify (or express) server to vue.js 3. Is there a way I can do this (I saw something called express-vue: github link, but it's for vue 2 and not official, so I don't know if it's any good)? And can you include the hydration of the client, because I saw some examples like https://github.com/moduslabs/vue3-example-ssr but it does not include the hydration of the client, if this is not possible I would use ejs, but I prefer vue 3. Can you give me an example or template? Thank you in advance! </p>
P粉078945182
P粉078945182

reply all(1)
P粉336536706

You can translate the above content into Chinese:

<p>您可以将上下文对象传递给renderToString函数</p>
<pre><code>const context = { data: 'Hello world' } // 您想要共享的数据
const html = renderToString(App, context)
</code></pre>
<p>在Vue组件中,可以使用useSSRContext来访问此对象</p>
<pre><code>setup() {
    if (typeof window === 'undefined') {
        const context = useSSRContext()
        console.log(context.data) // Hello world
    }
}
</code></pre>
<p>与Vue 2不同,您无需在<div id="app">中添加data-server-rendered="true",当您在浏览器上使用createSSRApp而不是createApp时,Vue 3会自动进行客户端渲染</p>
<hr />
<p>要在浏览器中传递对象,您需要在从服务器返回结果时将其写入<head>中的window变量中</p>
<pre><code>const html = renderToString(App, context)

res.send(`
    <html>
    <head>
        <script>window.context = ${JSON.stringify(JSON.stringify(context))}</script>
    </head>
        <body><div id="app">${html}</div></body>
        <script src="main.js"></script>
    </html>
`)
</code></pre>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template