3
votes

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?

1
Notice that data is bad name for property, because in Vue-component data means data-model, it is kind of reserved word. - hedin

1 Answers

5
votes

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">