- 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/).
- 6G潛在關鍵技術(下冊)
- 高校網絡道德教育研究
- 物聯網工程規劃技術
- Building E-commerce Sites with VirtueMart Cookbook
- Truffle Quick Start Guide
- 新一代物聯網架構技術:分層算力網絡
- 網絡的琴弦:玩轉IP看監控
- 計算機網絡與通信(第2版)
- Wireshark網絡分析就這么簡單
- Mastering TypeScript 3
- OMNeT++與網絡仿真
- 現場綜合化網絡運營與維護:運營商數字化轉型技術與實踐
- Enterprise ApplicationDevelopment with Ext JSand Spring
- 互聯網安全的40個智慧洞見(2018)
- Hands-On Microservices:Monitoring and Testing