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