Search code examples
loopsvue.jspropertiesundefinedv-for

vue js cannot read property of undefined


I use a v-for loop to list buttons for each category in my array. A function is called on click but it returns an error:

TypeError: Cannot read property 'name' of undefined

Every button is properly displayed in HTML with its name.

v-for loop:

<button :class="{selected: category.exist === true}" v-for="category in categories" :key="category.id" v-on:click="pushFilter(); category.exist = !category.exist">{{ category.name }} {{ category.exist }}</button>

categories data:

export default {
  data: function () {   
    return {
      categories: [
        {
          name: 'name1',
          exist: false,
        },
        {
          name: 'name2',
          exist: false,
        },
      ],

Method:

methods: {
  pushFilter() {
    console.log(this.category.name);
  },
}

Solution

  • pushFilter() references this.category, but the component has no category prop (at least none shown in question). You're probably trying to access the category iterator of v-for. You could just pass that in the template binding:

    <button v-for="category in categories" v-on:click="pushFilter(category)">
    

    And update your method to receive the category argument:

    export default {
      methods: {
        pushFilter(category) {
          console.log(category.name)
        }
      }
    }