Phil Samson
Phil Samson

Reputation: 61

Passing an Array as Prop, using v-for in the child does not work

In vue, i want my parent to pass an array to a child as a prop. The child then should render all contents of that array with v-for.

I used :steps="[1, 2, 3]" to pass in the array as prop and used a div as container with :for="step in steps", but it only renders one div with no content.

*** parent.vue template:

    <recipesListItem
      title="Name"
      description="text"
      :steps="[1, 2, 3]">
    </recipesListItem>

*** child.vue template:

    <div>
      {{ title }}<br>
      {{ description}}
      <div :for="step in steps">
        {{ step }}
      </div>
    </div>

*** child.vue script:

    import Vue from 'vue'

    export default Vue.extend({
      name: 'recipesListItem',
      props: {
           [ ... ]
      steps: Array
      }
    })    

Expected result: title, description and 3 divs with the contents "1", "2" and "3" are shown
Actual result: title description and only 1 div with no content is shown

Thanks in advance for any help

Upvotes: 1

Views: 2204

Answers (1)

Rubanraj Ravichandran
Rubanraj Ravichandran

Reputation: 1293

Change your child.vue template like this.

<div>
  {{ title }}<br>
  {{ description}}
  <div v-for="step in steps" :key="step">
    {{ step }}
  </div>
</div>

You should "v-for" to render a list or array and don't forget to bind key which is important for rendering. May be :key binding is not required for simple array like in your case. And if you do bind :key with your "step" then remember that your "step" values should be unique else you can use the following approach.

<div>
  {{ title }}<br>
  {{ description}}
  <div v-for="(step,index) in steps" :key="index">
    {{ step }}
  </div>
</div>

Also, you can use vue chrome debugger to make sure your list passed down to child component and available for rendering. In the below pic, App is parent component & HelloWorld is child component.

enter image description here

Upvotes: 2

Related Questions