簡體   English   中英

在Vue中使用服務器端渲染時異步數據更改

[英]Async data change when using server side render in Vue

我想在服務器端渲染中使用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內容數據一起呈現?

根據vue-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)
    }
})

這是工作中的小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM