简体   繁体   English

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

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

I want to use Vue in server side rendering , but the content data inside template have to request from the other CMS server. 我想在服务器端渲染中使用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>

Due to axios.get is an async request, server will send empty content before request complete. 由于axios.get是异步请求,因此服务器将在请求完成之前发送空内容。

Use curl to request content: 使用curl请求内容:

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

How do I make sure it can render with CMS content data in server side? 如何确保它可以在服务器端与CMS内容数据一起呈现?

According to vue-hackernews-2.0 example, src/server-entry.js will detect preFetch function in current route component. 根据vue-hackernews-2.0的示例, src / server-entry.js将检测当前路由组件中的preFetch函数。

So, just add a preFetch function in current route component and save the data to Vuex store. 因此,只需在当前路由组件中添加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>

You have to make following changes in the code: 您必须在代码中进行以下更改:

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

Here is a working fiddle . 这是工作中的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM