2

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? Commented Nov 11, 2016 at 7:04
  • When I use curl, it just got <h1></h1>, not <h1>Page Title</h1> Commented Nov 11, 2016 at 7:18

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

That is an ES6 arrow function, no need to create a self variable.
Yes, it definitely works on client side, but I want sever side render.
And why you make content become a global variable?
Ahh, Here is fiddle without making it global var.
@saurabh I think he means server side, it's working only in client side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.