vue-easy-renderer
是一个基于 vue-server-renderer
的服务端渲染工具,他提供了更简单的方式来实现vue的服务端渲染,支持koa.js
和express.js
安装
npm install vue-easy-renderer -S
Peer Dependency
npm i vue vuex vue-router vue-loader vue-server-renderer -S
Example
首先创建一个vue文件,路径如下 component/hello_word/hello_word.vue
<template>
<div>hello {{world}}</div>
</template>
<style scoped>
</style>
<script>
export default {
name: 'HelloWorld',
data() {
return {
world: ''
};
}
}
</script>
以express.js
为例创建以下文件
'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;
最后浏览器获取到的html
<html>
<head>
<script>window.__VUE_INITIAL_STATE__ = {"world":"world!"};</script>
</head>
<body>
<div server-rendered="true" data-v-30ca8d89>hello world!</div>
</body>
</html>
Component Head
我们可以在组件中设置html的头部
<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>
最终渲染的结果
<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实例,因此在根组件注入vuex或者vue-router实例时,需要在实例上添加一个工厂方法,该方法调用时返回一个实例,默认方法名为$ssrInstance
,如:
vuex
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