Home » vue » how to set the data object in a vue-resource such that it won't error in console

how to set the data object in a vue-resource such that it won't error in console

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am learning Vue this weekend so a very simple question.

I’m trying to convert some jQuery to using Vue with vue-resource. I am getting back data for a location with items. The problem I’m having is that whenever I load this object, I get an error saying the location is null (which is what I set it to be in data. What is the proper way to do this? Should I have a guard statement to prevent it rendering through items? If it was an array of locations, I could set to an empty array but for a single object, it seems like should be null. How best to have an empty data object that is filled via an async call?

const Location = {
    data(){
       return {location: null }
    },
     template: `<div>{{location.name}}
                   <div v-for="item in location.items">
                     <div>{{item.id}}</div>
                   </div>
                </div>`,
        created(){
          this.fetchData();
       },
       methods: {  fetchData(){
         this.$http.get('/arc/api/v1/site_admin/locations/' + this.$route.params.id + '/dashboard').then((response) => {
           console.log(response.data);
           this.location = response.data.location
        }).catch( error => { console.log(error); });
       }
     }
}
Answers:

The error you’re receiving is due to your template attempting to render with location set to null as you’ve noted. In these instances, you should use v-if to tell the part of the template that deals with a populated location that it should not render unless one is set:

<div v-if="location">
  {{ location.name }}

  <div v-for="item in location.items">
    <div>{{ item.id }}</div>
  </div>
</div>

PS: vue-resource has been officially marked as no longer undergoing active development. Though there are no issues with using it, you should consider using an alternative AJAX library like axios instead, to future-proof your journey with Vue.