使用Vue3.js + Rendertron创建SSR服务端渲染应用

文档

使用Vue3.js创建CSR客户端渲染应用

在这里插入图片描述

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <div id="app">{
   
   { message }}</div>

    <script>
      const {
      
       createApp } = Vue;

      createApp({
      
      
        data() {
      
      
          return {
      
      
            message: "Hello Vue!",
          };
        },
      }).mount("#app");
    </script>
  </body>
</html>

启动静态服务器

npx http-server -c-1

访问:http://127.0.0.1:8082/

浏览器获取的内容


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <div id="app">{
   
   { message }}</div>

    <script>
      const {
      
       createApp } = Vue;

      createApp({
      
      
        data() {
      
      
          return {
      
      
            message: "Hello Vue!",
          };
        },
      }).mount("#app");
    </script>
  </body>
</html>

使用Vue3.js + Rendertron创建SSR服务端渲染应用

在这里插入图片描述

安装启动

# 安装
pnpm install rendertron

# 启动
npx rendertron

渲染刚刚创建的Vue.js应用

http://localhost:3000/render/<url>

eg:

http://localhost:3000/render/http://127.0.0.1:8082/

返回客户端的html


<!DOCTYPE html><html lang="en"><head><base href="http://127.0.0.1:8082/">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    

    <div id="app" data-v-app="">Hello Vue!</div>

    
  

</body></html>

服务端可根据请求头 User Agent,判断如果是Baiduspider,返回渲染后的页面
在这里插入图片描述

参考
快速在你的vue/react应用中实现ssr(服务端渲染)

猜你喜欢

转载自blog.csdn.net/mouday/article/details/127208853