lukechambers91
lukechambers91

Reputation: 711

How to pass v-for index to child in Vue?

I have the below parent and child components. In the parent I am using obj.Array with v-for to list multiple children components. The issue is that stuff1 and stuff2 will be the same for each child but I need to grab each element of obj.array for each child. What is the correct way to do this? Thanks

Parent:

<template>
  <div>
    <child v-bind:obj="obj" v-for="(arrVal, index) in obj.array" :id="index" :key="arrVal"/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      obj: { stuff1: "str1", stuff2: "str2", array: ["arrVal1", "arrVal2", "arrVal3"] }
    };
  }
};
</script>

Child:

<template>
  <div>
    <p>{{obj.stuff1}}</p>
    <p>------</p>
    <p>{{obj.stuff2}}</p>
    <p>------</p>
    <p>{{obj.array[index]}}</p>
  </div>
</template>

    <script>
export default {
  props: { obj: Object }
};
</script>

What I would like to render:

str1 ------ str2 ------ arrVal1

str1 ------ str2 ------ arrVal2

str1 ------ str2 ------ arrVal2

Upvotes: 1

Views: 1397

Answers (1)

Michael
Michael

Reputation: 5048

try this:

<template>
  <div v-for="val in obj.array">
    <p>{{obj.stuff1}}</p>
    <p>------</p>
    <p>{{obj.stuff2}}</p>
    <p>------</p>
    <p>{{val}}</p>
  </div>
</template>

    <script>
export default {
  props: { obj: Object }
};
</script>

What I am suggesting is just to iterate over the array in the child component.

Upvotes: 1

Related Questions