Rest API doesn't load data quick enough before the route is shown using vue.js and vue-router

ぃ、小莉子 提交于 2019-12-12 10:27:08

问题


Using Vue.js with vue-router in unison with WP Rest API 2. When I switch to a route I see the div appear that should hold the content, and then the content finally loads. I also get this error:

[Vue warn]: Error when evaluating expression "content.content.rendered": TypeError: Cannot read property 'rendered' of undefined

The content will load on a computer eventually, even with the error, but on mobile the content doesn't show up at all. This is my method do grab a specific page. I have tried using nextTick but couldn't get it to function correctly.

Any help would be greatly appreciated, and please let me know if you need more information.

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


回答1:


Use vue-router's data hook.

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

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

Then, in the template:

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



回答2:


A simple fix is to prevent Vue from trying to access the object property:. First set the initial content value to null, based on your example, there is no reason to set is as an empty array. Looks like it will get assigned an object from your response data. Then, in your view, just do this:

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


来源:https://stackoverflow.com/questions/37731656/rest-api-doesnt-load-data-quick-enough-before-the-route-is-shown-using-vue-js-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!