search
HomeWeb Front-endVue.jsHow to do server-side rendering in Vue?

Vue is a popular JavaScript framework that provides tools and components for easy building user interfaces. As web applications become more complex, server-side rendering (SSR) can provide better performance and user experience. Vue 2.0 introduces SSR support, allowing us to use Vue for SSR. This article explains how to do server-side rendering in Vue.

What is server-side rendering?

In a typical client-side rendering application, the browser loads HTML pages and JavaScript files. When a user interacts with an application, JavaScript sends requests to the server, gets data, and updates the page. This approach can provide a great user experience, but it can also bring some drawbacks. First, search engine crawlers typically do not execute JavaScript, which means we may not be able to include all pages of your application. Second, the initial load time can be slow because the browser needs to wait for the JavaScript to download and execute before it can start rendering the interface.

Server-side rendering solves these problems. In SSR, the server sends HTML and JavaScript together to the browser when rendering the page. This means search engines can easily crawl the site, and initial page load times are faster because the browser doesn't need to wait for JavaScript to download before starting rendering. Additionally, SSR can improve application performance on low-end devices, which often lack powerful JavaScript engines.

Why use SSR in Vue?

Vue is a client-side rendering framework. It uses virtual DOM and asynchronous components to provide blazingly fast page response times. However, as applications become more complex, client-side rendering introduces some drawbacks. For example:

  • Long initial load time: Because the browser needs to download and execute JavaScript files, the initial load time of your application can be long.
  • Limited SEO support: Search engines generally do not execute JavaScript, which means we may not be able to index all pages.
  • Not good for low-end devices: Some low-end devices may not be able to handle large amounts of JavaScript, causing the app to become sluggish or crash.
  • Hard for crawlers: Since search engines cannot execute JavaScript, we may not be able to get crawlers to index our pages correctly.

SSR can solve the above problems and provide better performance and user experience. Therefore, Vue provides SSR support, allowing us to render Vue applications on the server side.

Steps to perform SSR in Vue

Conducting SSR in Vue is divided into the following steps:

  1. Create a Vue application instance.
  2. Create and configure a server (Node.js).
  3. Configure the server to handle our Vue application.
  4. Create a route to handle our page path.
  5. Render our Vue application in the server.

Now let’s look at each step step by step to understand SSR better.

Step 1: Create a Vue application instance

First, we need to create a Vue instance and define the application's template. When rendering client-side, we usually define the application's template in the index.html file. But in SSR, we need to create it on the server side. Here is a simple example:

// app.js
import Vue from 'vue';
import App from './App.vue';

export function createApp() {
  return new Vue({
    render: h => h(App)
  });
}

The code above exports a function named createApp that creates and returns a new Vue instance. This instance uses our root component App.vue to render the application.

Step 2: Create and configure a server

In step 1, we created a Vue instance that can be used to render our Vue application server-side. Now, we need to create a server to run this instance. We use Node.js to create the server.

Here are the basic server templates we can use:

// server.js
const express = require('express');
const app = express();

// The port number to use.
const PORT = process.env.PORT || 3000;

// Serve static assets.
app.use(express.static('public'));

// Start the server.
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

The code above creates a simple Express server and has it listen on local port 3000. This server can also use the express.static middleware to provide static file access support.

Step 3: Configure the server to handle our Vue application

We have created the server, now we need to configure the server to handle our Vue application. For this we need to use the vue-server-renderer dependency. The following is a complete code example:

// server.js
const express = require('express');
const app = express();

// Include the Vue SSR renderer.
const renderer = require('vue-server-renderer').createRenderer();

// Import the createApp function from app.js.
const { createApp } = require('./app');

// The port number to use.
const PORT = process.env.PORT || 3000;

// Serve static assets.
app.use(express.static('public'));

// Handle all GET requests.
app.get('*', (req, res) => {
  // Create a new Vue app instance.
  const app = createApp();

  // Render the Vue app to a string.
  renderer.renderToString(app, (err, html) => {
    if (err) {
      res.status(500).end('Internal Server Error');
      return;
    }

    // Send the HTML response to the client.
    res.end(`
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>Vue SSR App</title>
        </head>
        <body>
          ${html}
        </body>
      </html>
    `);
  });
});

// Start the server.
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

The above code creates a complete Express server, associates the request with the Vue instance, and uses the vue-server-renderer package The #renderToString method renders a Vue application to HTML.

Step 4: Create a Route

We are now able to render our Vue application server-side. Now we need to create a route that associates our page path with the server-side route. We use Vue Router to create routes.

The following is a simple example:

// app.js
import Vue from 'vue';
import App from './App.vue';
import { createRouter } from './router';

export function createApp() {
  const router = createRouter();

  return new Vue({
    router,
    render: h => h(App)
  });
}
// router.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

Vue.use(Router);

export function createRouter() {
  return new Router({
    mode: 'history',
    routes: [
      { path: '/', component: Home },
      { path: '/about', component: About }
    ]
  });
}

上面的代码分别在 app.jsrouter.js 文件中定义了我们的路由。在 app.js 文件中,我们创建了一个新的 Vue 实例并将路由器与其关联。在 router.js 文件中,我们使用 createRouter 函数来导出一个新的路由实例。

步骤5:在服务器中渲染我们的 Vue 应用程序

我们已经准备好工作了,现在需要在服务器中渲染我们的 Vue 应用程序。我们将使用步骤3中的代码,其中渲染器将 Vue 应用程序渲染为 HTML,最后将其发送回客户端。

现在让我们建立应用程序本身的代码。以下是我们简单的应用程序:

<!-- App.vue -->
<template>
  <div>
    <h1 id="message">{{ message }}</h1>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      message: 'Hello, Vue!'
    };
  }
};
</script>

在上面的组件中,我们定义了一个带有文本消息的标题。我们还使用 Vue Router 将组件关联到应用程序路径。

最后,在服务器上启动我们的应用程序。使用以下命令:

node server.js

现在,在浏览器中导航到 http://localhost:3000 应该显示我们的 Vue 应用程序。客户端和服务器端路由都应该正常工作。

结论

在本文中,我们了解了服务器端渲染 (SSR) 的概念。我们还了解了在 Vue 中执行服务器端渲染的步骤。我们了解了为什么在 Vue 中使用 SSR 很重要,以及如何使用 Node.js 和 vue-server-renderer 执行服务器端渲染。现在,你应该能够为你的下一个 Vue 应用程序使用 SSR 来提供更好的性能和用户体验。

The above is the detailed content of How to do server-side rendering in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment