vue.jsvue-component

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>

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>