简体   繁体   中英

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.

<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.

Use curl to request content:

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?

According to vue-hackernews-2.0 example, src/server-entry.js will detect preFetch function in current route component.

So, just add a preFetch function in current route component and save the data to Vuex store.

<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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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