- Vue.js 2 Design Patterns and Best Practices
- Paul Halliday
- 336字
- 2021-06-24 18:33:03
Server-Side Rendering (SSR)
Server-Side Rendering allows us to take our frontend JavaScript application and render it to static HTML on the server. This is important as it allows us to significantly speed up our application as the browser only has to parse the critical HTML/CSS. Maximizing performance is a key component of modern day web applications and the expectation continues to grow with progressive web applications and projects such as AMP. Both React, Angular and Vue are capable of SSR using a variety of different patterns.
Let's take a look at how we can achieve a simple Server-Side rendered Vue application:
# Create a new folder named vue-ssr:
$ mkdir vue-ssr
$ cd vue-ssr
# Create a new file named server.js
$ touch server.js
# Install dependencies
$ npm install vue vue-server-renderer express
Inside server.js, we can create a new Vue instance and use the Vue renderer to output the content of our instance as an HTML:
const Vue = require("vue");
const server = require("express")();
const renderer = require("vue-server-renderer").createRenderer();
server.get("*", (req, res) => {
const app = new Vue({
data: {
date: new Date()
},
template: `
<div>
The visited time: {{ date }}
</div>`
});
renderer.renderToString(app, (err, html) => {
if (err) {
res.status(500).end("Internal Server Error");
return;
}
res.end(`
<!DOCTYPE html>
<html lang="en">
<head><title>Hello</title></head>
<body>${html}</body>
</html>
`);
});
});
server.listen(8080);
To run the application, type the following in the Terminal:
$ node server.js
We can then open this in our browser at http://localhost: 8080 and we'd see the current date and time on screen. This is a simple example but we were able to see our application rendered using the vue-server-renderer. Notice how we're not defining a target element to render content within our Vue instance; this is handled by the renderer.renderToString function.
You'll also notice that we have the data-server-rendered="true" attribute on our DOM node, which isn't present on a client-side rendered Vue application. This allows us to hydrate our client-side instance with our server-side instance, something we'll be looking at more detail in the later chapter(s) on Nuxt (https://nuxtjs.org/).
- 通信網絡基礎與設備
- 網絡協議工程
- C++黑客編程揭秘與防范
- 面向物聯網的CC2530與傳感器應用開發
- 從區塊鏈到Web3:構建未來互聯網生態
- Django 2 by Example
- Learning QGIS 2.0
- Getting Started with Grunt:The JavaScript Task Runner
- Kong網關:入門、實戰與進階
- AWS Lambda Quick Start Guide
- 圖神經網絡前沿
- 工業以太網技術:AFDX/TTE網絡原理、接口、互連與安全
- Hands-On Reactive Programming in Spring 5
- SEO攻略:搜索引擎優化策略與實戰案例詳解
- 現場總線與工業以太網及其應用技術(第2版)