Home > database >  What causes the 'Cannot read properties of undefined error' in this Vue 3 application?
What causes the 'Cannot read properties of undefined error' in this Vue 3 application?

Time:04-12

I am working on a Vue 3 app. I have 3 nested components: a dropdown component, which is nested inside a navigation component, which is nested inside a content component.

The dropdown should filter posts inside the grandparent component Main.vue by author.

I tried to emit a getPostsByUser(user) method upwards, one component at a time.

In the grandchild component UsersDropdown.vue:

<template>
  <div >
    <button type="button"  data-bs-toggle="dropdown" aria-expanded="false">
       {{ label }}
    </button>
    <ul v-if="usersData?.length" >
      <li v-for="user in usersData" :key="user.userId">
        <a  @click="handleClick(user)">{{ user.first_name }} {{ user.last_name }}</a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'UsersDropdown',
  props: {
    label: String,
    usersData: Object,
    user: Object
  },

  methods: {
    handleClick(user) {
      this.$emit('getPostsByUser', user.userId)
    }
  }
}
</script>

In the parent component Navigation.vue:

<template>
    <div >
        <UsersDropdown
            @getPostsByUser="$emit('getPostsByUser', user)"
            :label='"All users"' 
            :usersData='users'
        />
    </div>
</template>

<script>
    import UsersDropdown from './UsersDropdown'


export default {
    props: {
        usersData: Object,
    },

  components: {
   UsersDropdown,
  },

    emits: ['getPostsByUser'],

    data() {
        return {
          users: [],
                gateways: []
        }
      },
      async mounted() {
        // Users
        await this.axios.get(`${this.$apiBaseUrl}/users`).then((response) => {
          if (response.data.code == 200) {
            this.users = response.data.data;
          }
        }).catch((errors) => {
          console.log(errors);
        });
      }
    }
</script>

In the grandparent component Main.vue:

<template>
  <div >
    <Navigation 
        @getPostsByUser='getPostsByUser(user)'
            :label='"All users"' 
            :usersData='users' />
  </div>
</template>

<script>
import Navigation from './Ui/Navigation'

export default {
   name: 'Main',
   components: {
    Navigation
  },
   props: {
    title: String,
    tagline: String,
   },
  
   data() {
     return {
      userId: '',
      posts: [],
      // more code
     }
  },
  
  methods: {
      getPostsByUser(user) {
      // get user id
      this.userId = user.userId;
    },
  }
}
</script>

The problem

For a reason I was unable to understand, the Chrome console throws the error:

Cannot read properties of undefined (reading 'userId')

Where is my mistake?

CodePudding user response:

The issue is with your Navigation component. You need to declare props and components in export default {} for them to work and pass the data.
Add the below code to it:

components: {
   UsersDropdown,
},
props: {
   usersData: Object,
},

Also, update your usersData prop mapping to UsersDropdown component tag in the HTML part of Navigation.vue component.
Replace existing with:

<UsersDropdown
   @getPostsByUser="$emit('getPostsByUser', user)"
   :label="'All users'"
   :usersData="usersData"
/>

In your `Navigation.vue` component, you need to declare a method to listen to the incoming `user` data and then emit the data again to the parent `Main.vue` component. You're trying to do it directly hence the undefined issue.
Update you `UsersDropdown` component tag as below:
<UsersDropdown
   @getPostsByUser="getPostsByUser"
   :label="'All users'"
   :usersData="usersData"
/>

Along with that add the following method to the export default {} section of Navigation.vue component.

methods: {
getPostsByUser(user) {
  // get user id
  console.log(user, "js");
  this.$emit("getPostsByUser", user);
},

},
And finally, update your @getPostsByUser event listener with just the respective function name. Passing of the argument isn't needed.
Replace @getPostsByUser="getPostsByUser(user)" with @getPostsByUser="getPostsByUser" in the Navigation tag of the HTML in Main.vue component.

For more clear understanding try this sandbox: https://codesandbox.io/s/vue-3-event-handling-nested-comps-s626kp?file=/src/App.vue

CodePudding user response:

In UsersDropdown.vue you are passing userId and in Main.vue you are awaiting whole user object , try with this.userId = user;

const app = Vue.createApp({
  el: "#demo",
  props: {
    title: String,
    tagline: String,
  },
  data() {
    return {
      userId: '',
      posts: [],
      // more code
    }
  },
  methods: {
    getPostsByUser(user) {
      this.userId = user;
    },
  }
})
app.component("Navigation", {
  template: `
    <div >
      <users-dropdown
        @getpostsbyuser="getPostsByUser"
        :label='"All users"' 
        :users-data='users'
      ></users-dropdown>
    </div>
  `,
  props: ['usersData'],
  data() {
    return {
      users: [],
      gateways: []
    }
  },
  async mounted() {
    // Users
    /*await this.axios.get(`${this.$apiBaseUrl}/users`).then((response) => {
      if (response.data.code == 200) {
        this.users = response.data.data;
      }
    }).catch((errors) => {
      console.log(errors);
    });*/
    this.users = [{userId: 1, first_name: "aaa", last_name: "bbb"}, {userId: 2, first_name: "ccc", last_name: "ddd"}, {userId: 3, first_name: "eee", last_name: "fff"}]
  },
  methods: {
    getPostsByUser(user) {
      this.$emit('getpostsbyuser', user);
    },
  }
})
app.component("UsersDropdown", {
  template: `
    <div >
      <button type="button"  data-bs-toggle="dropdown" aria-expanded="false">
       {{ label }}
      </button>
      <ul v-if="usersData?.length" >
        <li v-for="user in usersData" :key="user.userId">
          <a  @click="handleClick(user)">
            {{ user.first_name }} {{ user.last_name }}
          </a>
        </li>
      </ul>
    </div>
  `,
  props: {
    label: String,
    usersData: Array,
  },
  methods: {
    handleClick(user) {
      this.$emit('getpostsbyuser', user.userId)
    }
  }
})
app.mount('#demo')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p" crossorigin="anonymous"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div >
    <navigation @getpostsbyuser='getPostsByUser' :label='"All users"'></navigation>
    <p>user id: {{ userId }}</p>
  </div>
</div>

  • Related