[Vuejs]-Output values from nested Api/Laravel Collection response in vuejs

0👍

Your user variable will initially be null, and you can’t get properties from a null value. Therefore, you should replace {{ user.surname }} With {{ user ? user.surname : '' }}.

Another issue is that the data property from your response is an array, not an object, so in your mounted hook you can’t do this.user = response.data.data. Instead, you should do this.user = response.data[0].data.

That way, while your user isn’t fetched you’ll display an empty text instead of getting an error.

Also, I suggest you add a catch hook to your promise to tend to any possible errors.

👤Ayrton

1👍

<template> 
  <div> 
     {{surname}}
  </div>
</template>
<!-- ----------------------------------------------------------------------------------- -->

<script>
   export default {
   name: 'EmployeeCard',

   data(){
     return{
       user: null
     }
   },

   computed: {
    surname () {
     if (this.user) {
      return this.user.surname
     }
    }

   }

   methods:{
     getUser(){
       axios.get('/api/users/'+ this.$route.params.id)
            .then ( response => {
                    this.user = response.data[0].data; 
             })
     }
  },

  mounted(){
     this.getUser();
  }

  }
</script>

0👍

<template> 
  <div> 
      {{ user.surname }}
  </div>
</template>

<script>
    export default {
    name: 'EmployeeCard',

    data(){
        return{
            user: {}
        }
    },

    methods:{
        getUser(){
            axios.get('/api/users/'+ this.$route.params.id)
        .then ( {data} => {
                this.user = data[0].data; 
         })
        }
    },

    mounted(){
        this.getUser();
    }
}
</script>

Leave a comment