服务端渲染
https://ssr.vuejs.org/guide/universal.html#data-reactivity-on-the-server
npm install vue vue-server-renderer —save
// Step 1: Create a Vue instance
const Vue = require('vue')
const app = new Vue({
data: function () {
return {
message: 'Hello World'
}
},
template: `<div>{{message}}</div>`
})
// Step 2: Create a renderer
const renderer = require('vue-server-renderer').createRenderer()
// Step 3: Render the Vue instance to HTML
renderer.renderToString(app, (err, html) => {
if (err) throw err
console.log('renderToString:', html)
// => <div data-server-rendered="true">Hello World</div>
})
// in 2.5.0+, returns a Promise if no callback is passed:
renderer.renderToString(app).then(html => {
console.log('renderToString 2.5.0+:', html)
}).catch(err => {
console.error(err)
})
<!-- index.template.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- 非 HTML 转译 -->
<title>{{ title }}</title>
<!-- HTML 转译 -->
{{{ mate }}}
</head>
<body>
<!--vue-ssr-outlet-->
</body>
</html>
const Vue = require('vue')
const server = require('express')()
const serverRenderer = require('vue-server-renderer')
const renderer = serverRenderer.createRenderer({
template: require('fs').readFileSync('./index.template.html', 'utf-8')
})
const context = {
title: 'vue ssr',
mate: `
<meta charset="utf-8" />
`
};
server.get('*', (req, res) => {
const app = new Vue({
data: {
url: req.url
},
template: `<div @click="test">The visited URL is: {{ url }}</div>`,
methods: {
test() { // 服务端渲染后,在客户端没有效果
console.log('999')
}
}
})
serverRenderer.createRenderer().renderToString(app).then(html => {
context.app = html;
renderer.renderToString(app, context, (err, html) => {
if (err) {
res.status(500).end('Internal Server Error')
return
}
res.end(html)
})
}).catch(err => {
console.error(err)
})
})
server.listen(8088)
{
"name": "vue-server-renderer-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"vue": "^2.6.14",
"vue-server-renderer": "^2.6.14"
}
}