Passing an array to a prop in Vuejs

18,393

Like this you will receive in the child component array of names, and index of the current item, so you can get just the name of the item in the child component.

Also don't forget to add unique key where you use v-for directive.

Parent.vue

<template>
  <div>
    <child
      v-for="(skill, index) in skills.length"
      :key="skill.name"
      :index="index"
      :names-array="skills.map(a => a.name)"
    />
  </div>
</template>

<script>
import Child from './Child'

export default {
  name: 'Parent',

  components: {
    Child
  },

  data () {
    return {
      skills: [
        {
          name: 'Frozen Yogurt',
          required: 1,
          vMode1: ''
        },
        {
          name: 'Ice cream sandwich',
          required: 3,
          vMode1: ''
        },
        {
          name: 'Eclair',
          required: 1,
          vMode1: ''
        }
      ]
    }
  }
}
</script>

Child.vue

<template>
  <div>
    <div>Index: {{ index }}</div>
    <div>Names Array: {{ namesArray }}</div>
    <div>Name: {{ namesArray[index] }}</div>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: ["names-array", "index"]
};
</script>

Output:

Index: 0 Names Array: [ "Frozen Yogurt", "Ice cream sandwich", "Eclair" ] Name: Frozen Yogurt

Index: 1 Names Array: [ "Frozen Yogurt", "Ice cream sandwich", "Eclair" ] Name: Ice cream sandwich

Index: 2 Names Array: [ "Frozen Yogurt", "Ice cream sandwich", "Eclair" ] Name: Eclair

Share:
18,393
seyet
Author by

seyet

Updated on June 25, 2022

Comments

  • seyet
    seyet about 2 years

    I pass a list of values from a parent component to its child and want to receive all of the values but I only receive the last one.

    This is the code for the parent component:

         <app-spider-web
         v-for="skill in skills"
         :name="skill.name"
         :required="skill.required"
         :vMode1="skill.vMode1"
         ></app-spider-web>
    
       ...       
    
    
       skills: [
          {
            name: 'Frozen Yogurt',
            required: 1,
            vMode1: ''
          },
          {
            name: 'Ice cream sandwich',
            required: 3,
            vMode1: ''
          },
          {
            name: 'Eclair',
            required: 1,
            vMode1: ''
          }
        ]
    

    And this is the code for the child component:

    props:['name','required','vMode1']
    

    This way I receive the data one by one and if I want print for instance 'name' it only shows the last name in the list which is 'Eclair' whereas I want to have an array in child components with all the names in them. What's the best way to do it?