Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to child component in vue.js

I'm new to vue.js and I try to pass a value to the child component.

HTML

<div id="example">
   <my-component v-bind:data="parentData"></my-component>
</div>

JS

Vue.component('my-component', {
  props: ['data'],
  template: '<div>Parent component with data: {{ data.value }}!<div is="my-component-child" v-bind:data="childData"></div></div>'
});

Vue.component('my-component-child', {
  props: ['data'],
  template: '<div>Child component with data: {{ data.value }} </div>'
});

new Vue({
  el: '#example',
  data: {
    parentData: {
      value: 'hello parent!'
    },
    childData: {
      value: 'hello child!'
    }
  }
});

https://jsfiddle.net/v9osont9/2/

And I've got this error:

[Vue warn]: Property or method "childData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in )

[Vue warn]: Error in render function: (found in )

TypeError: Cannot read property 'value' of undefined

What is the proper way to do this?

like image 997
kojot Avatar asked Dec 08 '25 08:12

kojot


1 Answers

When you call

<my-component v-bind:data="parentData"></my-component> 

you are passing only the parentData to your parent component and childData gets out of scope.

You need to nest your childData in your parentData:

new Vue({
    el: '#example',
    data: {
        parentData: {
            value: 'hello parent!',
            childData: {
                value: 'hello child!'
            }
        }
    }
});

and pass it to your child like this:

<div is="my-component-child" v-bind:data="data.childData"> 
like image 195
ceferrari Avatar answered Dec 11 '25 23:12

ceferrari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!