2016-06-09 82 views
0

將vue.js與vue-router一起使用,並與WP Rest API 2一起使用,從而不會加載足夠快的數據。 當我切換到路由時, div出現應該保存內容,然後內容最終加載。我也收到此錯誤:Rest API使用vue.js和vue-router

[Vue公司提醒]:錯誤評估表達「content.content.rendered」時:類型錯誤:無法讀取的不確定

內容將在計算機上加載最終「渲染」屬性,即使出現錯誤,但在移動設備上,內容根本不會顯示。這是我的方法確實抓住特定頁面。我曾嘗試使用nextTick,但無法使其正常工作。

任何幫助將不勝感激,請讓我知道,如果你需要更多的信息。

<template> 

<div> 
<div class="animated cateringWrap"> 
    <h1>{{ content.title.rendered }}</h1> 
    {{{ content.content.rendered }}} 
</div> 
</div> 

</template> 



<script> 
export default { 
data() { 
    return { 
    content: [] 
    } 
}, 


ready: function(){ 
    this.loadContent(); 
}, 

methods: { 
    loadContent: function() { 
    this.$http.get('http://localhost/t/wp-json/wp/v2/pages/82').then(function(response){ 
     this.content = response.data; 
    }); 


    } 
} 

} 

</script> 

alt text http://oi67.tinypic.com/20ker05.jpg

+0

我建議在這裏發佈代碼,而不是圖像。 – crabbly

回答

1

使用VUE路由器的數據掛鉤。

http://router.vuejs.org/en/pipeline/data.html

route: { 
    data: function (transition) { 
    return this.$http.get(...); 
    } 
} 

然後,在模板:

<div v-if="$loadingRouteData">Loading ...</div> 
<div v-else>Your current HTML.</div> 
+0

我在index.js中調用路由 - 不確定我要添加代碼的位置。 ' router.map({ '/家':{ 組件:首頁 }, ' – 4ndy

+0

@ 4ndy的'路線:{}'塊進入你的'.vue'組件文件這是一個塊像' ready'或'methods'是 – ceejayoz

+0

這很好,但過渡效果已經消失了,我使用的是animate.css反彈效果,你基本上做了什麼就得到了一個預裝載器屏幕,謝謝你。現在雖然有更多的錯誤,但仍然是我試圖擺脫的錯誤: ** [Vue warn]:評估表達式「content.content.rendered」時出錯:TypeError:Can not read property' 'undefined ** The我現在得到的其他錯誤: – 4ndy

1

一個簡單的解決方法是防止Vue的嘗試訪問的對象屬性:。 首先將初始值content的值設置爲null,根據你的例子,沒有理由將其設置爲空數組。看起來它會從您的響應數據中分配一個對象。然後,在你看來,只要這樣做:

{{{ content ? content.content.rendered : null }}}