user992731
user992731

Reputation: 3520

Object error when iterating through VUE v-for loop

Pardon, my lack of knowledge here. Still getting the hang of Vue. I am trying to iterate through a loop and keep running into an issue when my length is a hardcoded value. I keep getting:

'"[Vue warn]: Error in render: 'TypeError: Cannot read property 'title' of undefined'

Js:

new Vue({
  el: '#app',
  data: {
    inputs: [],
    items: [
    { title: 'Blue' },
    { title: 'Yellow' },
    { title: 'Red' },
    { title: 'Purple' }
  ]
  }
})

Markup:

<div id="app">
 <ul>
  <li v-for="n in 4">
    <label>
      <input
        type="checkbox"
        v-model="inputs"
        :value="n"
        :disabled="inputs.length > 0 && inputs.indexOf(n) === -1" 
        > Item {{ items[n].title }}
    </label>
  </li>
</ul>
</div>

Upvotes: 0

Views: 632

Answers (2)

Cristian Silva
Cristian Silva

Reputation: 1

You made an incorrect loop... I don't know if the logics you made are correct, but this is how a vue js loop should be:

<li v-for="item in items">
    <label>
      <input :value="item"> 
      Item {{ item.title }}
    </label>
</li> 

After this, perhaps your console will show an error saying that li tag misses a key, then, see the docs https://v2.vuejs.org/v2/guide/list.html :)

Upvotes: 0

Jayce444
Jayce444

Reputation: 9063

v-for="n in 4" will mean that n is 1,2,3,4 - rather than 0,1,2,3. So it won't match with the indices of the array. You need to use the index of the loop counter, which is the second argument, i.e.

<li v-for="(n, i) in 4">

and then

{{ items[i].title }}

Upvotes: 1

Related Questions