Home » vue » Vuejs creating a list from an array

Vuejs creating a list from an array

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m having a strange problem creating a list with Vuejs. I have an array like so:

const sr = new Vue({
  el: '#singlerecipe-app',
  data: {
    checkeditems: [],
  },
});

And this is instantiated in my HTML like so:

<div class="container" id="singlerecipe-app">
  <singlerecipe :checkeditems="checkeditems"></singlerecipe>
</div>

And declared as a Prop in my component:

Vue.component('singlerecipe', {
  props: ['checkeditems'],
  template: `
    <ul>
       <li v-for="item of checkeditems">
           {{ item.checkeditems }}
       </li>
    </ul>
  `
})

The checked items code is:

<li v-if="result.strIngredient1">
    <input type="checkbox" :value="result.strIngredient1" :id="result.strIngredient1" v-model="checkeditems"> {{result.strIngredient1}} - {{result.strMeasure1}}
</li>
<li v-if="result.strIngredient2">
    <input type="checkbox" :value="result.strIngredient2" :id="result.strIngredient2" v-model="checkeditems"> {{result.strIngredient2}} - {{result.strMeasure2}}
</li>

If I click on one of the checkbox it definitely adds the correct value to the array checkeditems[] but oddly, it creates the new list items but doesn’t add the value so I end up with this:

<ul>
  <li></li>
  <li></li>
</ul>

With no value in the list item. Does anyone have any idea what I’m doing wrong?

Answers:

I think you’ve just accidentally added a ‘checkeditems’ in.

It should be:

Vue.component('singlerecipe', {
  props: ['checkeditems'],
  template: `
    <ul>
       <li v-for="item of checkeditems">
           {{ item }}
       </li>
    </ul>
  `
})