基础
- createApp: 创建应用,直接挂载到页面上
- createSSRApp: 创建应用,是在激活的模式下挂载应用
- 服务端用 @vue/server-renderer 包中的 renderToString 来进行渲染
实践
app.js
import { createSSRApp } from "vue";
import App from "./App.vue";
export default () => createSSRApp(App)
client.js
import { createApp } from 'vue'
import App from '../../App.vue'
createApp(App).mount('#app')
server.js
import Koa2 from 'koa'
import staticFiles from 'koa-static'
const { renderToString } = require('@vue/server-renderer')
const { default: app } = require('/app')
const server = Koa2()
server.use(staticFiles('public'))
server.use(async function (ctx) {
const req = ctx.request
if (req.path === '/favicon.ico') {
ctx.body = ''
return false
}
const htmlStr = await renderToString(app())
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
${htmlStr}
</div>
<script src="/client/client_server.js"></script>
</body>
</html>
`)
})
server.listen(3000)