服务端渲染

https://ssr.vuejs.org/guide/universal.html#data-reactivity-on-the-server
npm install vue vue-server-renderer —save

  1. // Step 1: Create a Vue instance
  2. const Vue = require('vue')
  3. const app = new Vue({
  4. data: function () {
  5. return {
  6. message: 'Hello World'
  7. }
  8. },
  9. template: `<div>{{message}}</div>`
  10. })
  11. // Step 2: Create a renderer
  12. const renderer = require('vue-server-renderer').createRenderer()
  13. // Step 3: Render the Vue instance to HTML
  14. renderer.renderToString(app, (err, html) => {
  15. if (err) throw err
  16. console.log('renderToString:', html)
  17. // => <div data-server-rendered="true">Hello World</div>
  18. })
  19. // in 2.5.0+, returns a Promise if no callback is passed:
  20. renderer.renderToString(app).then(html => {
  21. console.log('renderToString 2.5.0+:', html)
  22. }).catch(err => {
  23. console.error(err)
  24. })
  1. <!-- index.template.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <!-- 非 HTML 转译 -->
  6. <title>{{ title }}</title>
  7. <!-- HTML 转译 -->
  8. {{{ mate }}}
  9. </head>
  10. <body>
  11. <!--vue-ssr-outlet-->
  12. </body>
  13. </html>
  1. const Vue = require('vue')
  2. const server = require('express')()
  3. const serverRenderer = require('vue-server-renderer')
  4. const renderer = serverRenderer.createRenderer({
  5. template: require('fs').readFileSync('./index.template.html', 'utf-8')
  6. })
  7. const context = {
  8. title: 'vue ssr',
  9. mate: `
  10. <meta charset="utf-8" />
  11. `
  12. };
  13. server.get('*', (req, res) => {
  14. const app = new Vue({
  15. data: {
  16. url: req.url
  17. },
  18. template: `<div @click="test">The visited URL is: {{ url }}</div>`,
  19. methods: {
  20. test() { // 服务端渲染后,在客户端没有效果
  21. console.log('999')
  22. }
  23. }
  24. })
  25. serverRenderer.createRenderer().renderToString(app).then(html => {
  26. context.app = html;
  27. renderer.renderToString(app, context, (err, html) => {
  28. if (err) {
  29. res.status(500).end('Internal Server Error')
  30. return
  31. }
  32. res.end(html)
  33. })
  34. }).catch(err => {
  35. console.error(err)
  36. })
  37. })
  38. server.listen(8088)
  1. {
  2. "name": "vue-server-renderer-demo",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "author": "",
  10. "license": "ISC",
  11. "dependencies": {
  12. "express": "^4.17.1",
  13. "vue": "^2.6.14",
  14. "vue-server-renderer": "^2.6.14"
  15. }
  16. }