Home > Web Front-end > Vue.js > SSR function in Vue3: implementing server-side rendering

SSR function in Vue3: implementing server-side rendering

WBOY
Release: 2023-06-18 11:01:37
Original
3765 people have browsed it

With the popularization of mobile Internet and the rapid development of cloud computing technology, front-end framework has gradually become the main force of WEB development. In addition to providing convenient page structure, interactive effects and dynamic content display, the front-end framework also has the advantages of rapid development, maintainability, performance optimization, etc., which greatly improves development efficiency and user experience. As a popular front-end framework, Vue.js version 3.0 has been officially released, bringing more innovation and optimization. Among them, the implementation of Server Side Rendering (SSR) is an important update in Vue3.

1. The definition and advantages of SSR

SSR refers to completing the page rendering work on the server side, instead of using JavaScript to dynamically generate a DOM tree on the client side, so as to quickly improve page rendering. Speed ​​and SEO purposes. The traditional SPA (Single Page Application) architecture usually uses client-side rendering mode to display pages through Vue.js rendering on the client side. The advantages are good dynamic interactivity and good user experience. However, since the SPA can only display the page after the JavaScript is downloaded and parsed, there will be problems such as slow page loading and unfriendly SEO. SSR sends the server-side rendered HTML document to the client, which not only optimizes loading speed and SEO, but also has the advantages of better initial rendering performance, accessibility, and social sharing.

2. SSR implementation in Vue3

Vue.js provides a solution to support server-side rendering in version 2.0 to meet some special demand scenarios. In Vue3, SSR has received more complete support, the core of which is the createRenderer function. Next, let’s take a look at the SSR implementation in Vue3.

  1. Installation related dependencies

Vue3 officially provides two core dependencies: @vue/server-renderer and @vue/compiler-sfc. The former is used to generate HTML and CSS. , Script and other resources, and convert them into strings and return them. The latter provides compilation and parsing capabilities for .vue files, and can convert .vue files into rendering functions.

  1. Define the rendering function

Vue3 recommends using the render function instead of the template template. You can define the rendering function through the createRenderer function. The createRenderer function returns an object that contains the rendering function and other related information.

const { createRenderer } = require('@vue/server-renderer');
const renderer = createRenderer();
const app = require('./app');

renderer.renderToString(app).then((html) => {
  console.log(html);
}).catch((err) => {
  console.error(err);
});
Copy after login

Among them, app is a Vue instance, which needs to be initialized through the createApp function first, and then mounted on the DOM element. Next, you can use the rendering function to render the app.

  1. Create router and container components

Tools such as vue-router and vuex need to be used under SSR to support component and state management corresponding to different routes. Before doing this, you need to create the router and container components.

const { createRouter } = require('vue-router');
const App = require('./App.vue');

const router = createRouter({
  routes: [
    { path: '/', component: App }
  ]
});
Copy after login
  1. Write code to implement SSR
const express = require('express');
const { createSSRApp } = require('vue');

const server = express();
const template = `
  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Vue3 SSR</title>
    </head>
    <body>
      <!--vue-ssr-outlet-->
    </body>
  </html>
`;

const { createRenderer } = require('@vue/server-renderer');
const renderer = createRenderer({
  template: template
});

server.use(express.static('dist'));

server.get('*', async (req, res) => {
  const app = createSSRApp(require('./src/App.vue'));
  const router = require('./src/router').default;
  app.use(router);
  const html = await renderer.renderToString(app);
  res.send(html);
});

server.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});
Copy after login

When writing code to implement SSR, you need to create an express project and use the createSSRApp function to create a Vue instance, and then Routers, state management, createRenderer functions, etc. are all integrated.

3. Notes on SSR

When using SSR to implement page rendering, you need to pay attention to the following points:

  1. Need to rely on various external resources, including static Resources, data interfaces, databases, caches and file storage, etc. At the same time, it also brings more challenges to operation and maintenance students.
  2. Since server-side rendering requires at least as much time as rendering, the performance of SSR is mainly affected by server and network bandwidth, while the overall performance of the client will not have much impact.
  3. SSR needs to convert Vue components into string format for rendering, so it requires conversion and compilation of Vue components, which will bring a certain amount of consumption and compilation time.

In short, SSR is a relatively new technology, and you need to pay attention to the handling of various problems in terms of performance and use. You can make technology selection and actual use according to your own needs. Especially in large-scale real-time systems, special attention needs to be paid to the security, maintainability, and performance of SSR.

The above is the detailed content of SSR function in Vue3: implementing server-side rendering. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template