How to implement server-side rendering (SSR) in Vue 3

Today I'm going to introduce you to a cool feature - server-side rendering (SSR) in Vue 3

First, let's talk about what SSR is. It is like a magician, allowing your web pages to be pre-rendered on the server and then sent to the client. Imagine that you are browsing a webpage, click on the link, and the page will appear directly in front of you, just like magic, this is the function of SSR!

To use SSR in Vue 3, we need to first install a library called "vue-server-renderer". How to install? Haha, like this!

npm install vue-server-renderer

After the installation is complete, we can start using SSR!

First, we need to create a Vue instance on the server side.

import Vue from 'vue'  
import App from './App.vue'  
  
const serverVm = new Vue({
    
      
  render: h => h(App),  
  $server: true // 标记为服务器端渲染  
})

Then, we need to create a server to handle the request and send the response.

import http from 'http'  
import Vue from 'vue'  
import App from './App.vue'  
import serverVm from './server-vm' // 导入上面创建的服务器实例  
  
const server = http.createServer((req, res) => {
    
      
  serverVm.$mount('#app') // 将服务器实例挂载到根节点上  
  res.end('') // 结束响应,防止浏览器缓存此页,影响首屏渲染时间  
})

We'll also set some rules to make sure things work. This is some configuration we need to add in the server-side code.

const rendererOptions = {
    
      
  runInNewContext: false, // 确保在服务器端渲染时组件代码不会被执行两次  
} as VueServerRendererRenderOptions  
const renderer = Vue.createRenderer(rendererOptions) // 创建渲染器  
serverVm.$mount('#app', renderer) // 将服务器实例挂载到根节点上并使用渲染器进行渲染

Now, we're ready to render our Vue app on the server side! You can embed the above code into your server-side code, such as using a framework such as Express.js or Koa.js to create an HTTP server.

On the client side, you also need to load the HTML generated by Server Side Rendering (SSR). Here's a simple example showing how to load SSR-generated HTML in a Vue client.

// 这是一个在Vue客户端加载SSR生成的HTML的简单例子:  
import Vue from 'vue'  
import App from './App.vue'  
import serverVm from './server-vm' // 导入上面创建的服务器实例  
  
const clientVm = new Vue({
    
      
  render: h => h(App), // 使用客户端的App组件进行渲染  
  $server: true, // 标记为服务器端渲染已完成  
  $el: '#app', // 将根节点替换为客户端实例挂载的元素  
  beforeDestroy: () => {
    
     // 在客户端实例销毁前执行清理工作  
    serverVm.$destroy() // 销毁服务器端实例以释放内存和资源  
  }  
})

In Vue 3, when implementing server-side rendering (SSR), you need to pay attention to the following points:

Data passing
When you implement SSR in Vue 3, you need to ensure that data is passed correctly between the server and client. This can be done by appending data to the HTML when rendering on the server side, and then extracting the data from the HTML on the client side. Here is a simple example:

// 在服务器端渲染时,将数据附加到HTML中:  
const html = renderer.renderToString(App, {
    
     data: {
    
     message: 'Hello, world!' } })

Then on the client side, you can get the data through Vue's created() hook:

// 在客户端获取数据:  
export default defineComponent({
    
      
  created() {
    
      
    const data = JSON.parse(this.$el.getAttribute('data'))  
    console.log(data.message) // 输出:Hello, world!  
  }  
})

State Management
In SSR, you may need to manage global state to ensure that the state of the server and client remains consistent. This can be achieved by using Vue's global events or the Vuex state management library. Here is a simple example using Vuex:

First, install Vuex on the server side:

npm install vuex

Then create a store.js file:

// store.js  
import {
    
     createStore } from 'vuex'  
  
export default createStore({
    
      
  state: {
    
      
    count: 0  
  },  
  mutations: {
    
      
    increment(state) {
    
      
      state.count++  
    }  
  }  
})

In both server-side and client-side App components, store is introduced and mutations are used to modify the state:

// App.vue(服务器端)  
<script>  
import {
    
     mapMutations } from 'vuex'  
import store from './store' // 引入store.js  
export default defineComponent({
    
      
  setup() {
    
      
    const {
    
     count } = store.state // 获取状态  
    const increment = mapMutations('store', 'increment') // 映射mutations到组件中  
    return {
    
     count, increment } // 将状态和方法返回给模板使用  
  }  
})  
</script>

The above are the points that need to be paid attention to when implementing SSR in Vue 3. Of course, this is just a simple example, and more details may need to be considered in actual use, such as routing, security, and so on.

Guess you like

Origin blog.csdn.net/2301_77795034/article/details/131603472