简体   繁体   中英

TypeError :Cannot read property 'id' of undefined in Vue

I have created a component for the user profile. JSON data is coming from Laravel JWT authentication. But getting

TypeError: Cannot read property 'id' of undefined. same for the name also

<template>
  <div class="mt-3">
        <div class="alert alert-danger" v-if="has_error">
          <p>Something goes wrong</p>
        </div>
      <p>{{ user.id }}</p>
      <p>{{ user.name }}</p>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        has_error: false,
        user:{
          id:'',
          name:''
        }
      }
    },
    mounted() {
      this.getUsers()
    },
    methods: {
      getUsers() {
        this.$http({
          url: `auth/profile`,
          method: 'GET'
        })
            .then((res) => {
              this.user = res.data.user
            }, () => {
              this.has_error = true
            })
      }
    }
  }
</script>

Actual results must be: 1 Username

So, you properly defined user in component data . And the error you are getting might happen only in the case if res.data.user is undefined which you are getting from API in getUsers method. I suggest, there is no user object in response data. By that way res.data.user is undefined and as you reasigned this.user to be equal res.data.user it get undefined value too.

Instead of "this.user = res.data.user" we have to wight "this.user = res.data". And this solved this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM