Home  >  Article  >  Web Front-end  >  How to do server-side rendering in Vue?

How to do server-side rendering in Vue?

WBOY
WBOYOriginal
2023-06-11 19:28:352372browse

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>{{ 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