Sylvia
Sylvia

Reputation: 277

Vue - Cannot get parent's component data

I am new to Vue and I am trying to get parent's component data with props from a child component but I cannot get the parent's component data.

Could anyone tell me how can I do that?

Thank You.

window.onload = () => {
  var vm = new Vue({
    el:'#app',
    data:{
      a:'aaa'
    },

    components:{
      'aaa':{
           data(){
             return {
               msg:"parent's component data1",
               msg2:"parent's component data2"
             }
           },
        template:'#aaa',
        component:{
          'bbb':{
            props:['m','myMsg'],
            template:'<h3>{{m}} <br> {{myMsg}}</h3>'
          }
        }
      }
    }
  })
}
<div id="app">
  <aaa></aaa>
</div>
<template id='aaa'>
  <h2>aaa-->{{msg}}</h2>
  <bbb :m='msg' :myMsg='msg2'></bbb>
</template>

Upvotes: 1

Views: 143

Answers (1)

acdcjunior
acdcjunior

Reputation: 135752

Your aaa component's template didn't have a single root element. I added a <div> (see below).

Also, and more important, if the prop is myMsg pass it from the parent using :my-msg:

var vm = new Vue({
  el: '#app',
  data: {
    a: 'aaa'
  },
  components: {
    'aaa': {
      data() {
        return {
          msg: "parent's component data1",
          msg2: "parent's component data2"
        }
      },
      template: '#aaa',
      components: {
        'bbb': {
          props: ['m', 'myMsg'],
          template: '<h3>{{m}} <br> {{myMsg}}</h3>'
        }
      }
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<template id="aaa">
  <div>
    <h2>aaa--->{{msg}}</h2>
    <bbb :m='msg' :my-msg='msg2'></bbb>
  </div>
</template>

<div id="app">
  <aaa></aaa>
</div>

Upvotes: 3

Related Questions