2016-11-11 59 views
2

我想在服務器端渲染中使用Vue,但模板內的內容數據必須從其他CMS服務器請求。在Vue中使用服務器端渲染時的異步數據更改

<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內容數據呈現?

+0

這不行嗎? – Saurabh

+0

當我使用'curl'時,它剛剛獲得'

',而不是'

Page Title

' – Knovour

回答

2

根據vue-hackernews-2.0示例,src/server-entry.js將檢測當前路由組件中的​​函數。

因此,只需在當前路由組件中添加一個​​函數並將數據保存到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> 
0

你必須在代碼中進行以下更改:

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

這裏是一個工作fiddle

+0

這是一個ES6箭頭函數,不需要創建'self'變量。 – Knovour

+0

是的,它絕對適用於客戶端,但我希望切斷邊渲染。 – Knovour

+0

爲什麼你讓'content'成爲一個全局變量? – Knovour