vue-easy-renderer

leaves發表於2019-02-16

vue-easy-renderer 是一個基於 vue-server-renderer 的服務端渲染工具,他提供了更簡單的方式來實現vue的服務端渲染,支援koa.jsexpress.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,需要設定modehistory

專案地址

vue-easy-renderer