Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue – passing a data list to child component

I’ve looked over a few answers on here like this one and as far as I can see this should work to pass imported json data from the parent to the child component.

the import and looping through data works fine if I do it all in the parent with a v-for:

<div v-for="(product, index) in productData" :key="index">{{product}}</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but I just can’t get it to work if the loop is done in the child component.

PARENT COMPONENT

import productData from './assets/products.json'
import ChildComponent from './components/ChildComponent.vue'

export default {
  name: 'App',
  components: {
    ChildComponent
  },
  data(){
    return{
      productData: productData.products
    }
  }
}


<template>
    <ChildComponent :productsData="productData" />
</template>

CHILD COMPONENT

<template>
  <div v-for="(product, index) in productData" :key="index">{{product}}</div>
</template>

However this doesn’t render the looped data like it did when done in just the parent component and I can’t see what’s wrong from researching.

So any help would be much appreciated thanks

>Solution :

ParentComponent.vue

<template>
  <ChildComponent :productsData="productData" />
</template>

<script>
import productData from './assets/products.json'
import ChildComponent from './components/ChildComponent.vue'

export default {
  name: 'App',
  components: {
    ChildComponent
  },
  data() {
    return {
      productData: productData.products
    };
  }
};
</script>

ChildComponent.vue

<template>
  <div v-for="(product, index) in productsData" :key="index">
    {{ product }}
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    productsData: {
      type: Array,
      required: true
    }
  }
};
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading