2
votes

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?

2
Does this not work?Saurabh
When I use curl, it just got <h1></h1>, not <h1>Page Title</h1>Knovour

2 Answers

3
votes

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>
0
votes

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.