vue-easy-renderer
是一個基於 vue-server-renderer
的服務端渲染工具,他提供了更簡單的方式來實現vue的服務端渲染,支持koa.js
和express.js
css
npm install vue-easy-renderer -S
Peer Dependencyhtml
npm i vue vuex vue-router vue-loader vue-server-renderer -S
首先建立一個vue文件,路徑以下 component/hello_word/hello_word.vue
vue
<template> <div>hello {{world}}</div> </template> <style scoped> </style> <script> export default { name: 'HelloWorld', data() { return { world: '' }; } } </script>
以express.js
爲例建立如下文件git
'use strict'; const path = require('path'); const express = require('express'); const vueEasyRenderer = require('vue-easy-renderer').connectRenderer; const renderer = vueEasyRenderer(path.resolve(__dirname, './component')); const app = express(); app.use(express.static('./dist')); app.use(renderer); app.get('/', (req, res) => res.vueRender('hello_world/hello_world.vue', {world: 'world!'})); app.listen(8081); console.log('vue-easy-renderer express example start in 127.0.0.1:8081'); module.exports = app;
最後瀏覽器獲取到的htmlgithub
<html> <head> <script>window.__VUE_INITIAL_STATE__ = {"world":"world!"};</script> </head> <body> <div server-rendered="true" data-v-30ca8d89>hello world!</div> </body> </html>
咱們能夠在組件中設置html的頭部vue-router
<template> <div id="app" class="hello">hello {{world}}</div> </template> <style scoped> </style> <script> export default { name: 'HelloWorld', data() { return { world: '' }; }, head: { title: 'hello', script: [ {src: "/hello_world.js", async: 'async'} ], link: [ { rel: 'stylesheet', href: '/style/hello_world.css' }, ] }, } </script>
最終渲染的結果vuex
<html> <head> <title>hello</title> <link rel="stylesheet" href="/style/hello_world.css"/> <script>window.__VUE_INITIAL_STATE__ = {"world":"world!"};</script> <script src="/hello_world.js" async="true"></script> </head> <body> <div id="app" server-rendered="true" class="hello" data-v-035d6643>hello world!</div> </body> </html>
在服務端渲染中使用vuex或者vue-router時,咱們須要爲每一個請求建立一個vuex或者vue-router實例,所以在根組件注入vuex或者vue-router實例時,須要在實例上添加一個工廠方法,該方法調用時返回一個實例,默認方法名爲$ssrInstance
,如:express
vuexnpm
const options = { state: { hello: 'world!' } }; const store = new Vuex(options); store.$ssrInstance = () => new Vuex(options); export default store;
vue-router瀏覽器
const options = { mode: 'history', routes: [ { path: '/user/:id', component: User } ] }) const router = new VueRouter(options) router.$ssrInstance = () => new Vuex(options); export default router;
若是在服務端渲染中使用vue-router
,須要設置mode
爲history