在Vue中使用服务器端渲染时,异步数据更改

Async data change when using server side render in Vue

本文关键字:异步 数据 Vue 服务器端      更新时间:2023-09-26

我想使用Vue在服务器端呈现,但模板内的内容数据必须从其他CMS服务器请求。

<template>
  <h1>{{ content.heading }}</h1>
</template>
<script>
  export default {
    data() {
      return {
        content: {
          heading: ''
        }
      }
    },
    created() {
      axios
        .get(CONTENT_RESOURCE)
        .then(content => this.content = content);
    }
  }
</script>

由于axios.get是异步请求,服务器将在请求完成之前发送空内容。

使用curl请求内容:

curl 'URL';
# It got <h1></h1>,
# but I want <h1>Something here</h1>

我如何确保它可以在服务器端呈现CMS内容数据?

根据veu -hackernews-2.0示例,src/server-entry.js将检测当前路由组件中的preFetch功能。

因此,只需在当前路由组件中添加preFetch功能,并将数据保存到Vuex存储。

<template>
  <h1>{{ content.heading }}</h1>
</template>
<script>
  const fetchContent = store => 
    axios
      .get(CONTENT_RESOURCE)
      .then(content => store.dispatch('SAVE_CONTENT', content));
  export default {
    computed: {
      content() {
        return this.$store.YOUR_CONTENT_KEY_NAME
      }
    },
    preFetch: fetchContent,   // For server side render
    beforeCreate() {          // For client side render
      fetchContent(this.$store);
    }
  }
</script>

您必须在代码中做以下更改:

var demo = new Vue({
    el: '#demo',
    data:{
         content : {heading: ""}
    },
    beforeMount() {
      var self = this;
      setTimeout(function(){
          self.content.heading = "HI"
      }, 100)
    }
})