简体   繁体   中英

Vuejs - pass data from parent to child with props

I have started playing with Vue but faced an issue when trying to pass data to a component using props . In the code below this.myData (in the Hello.vue ) is undefined for some reason

App.vue

<script>
import Hello from './components/Hello'

export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  } ...
 </script>

Hello.vue

<script>
export default {
  name: 'hello',
  props: ['myData'],
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
  mounted: function() {
       console.log(this.myData)
   }
} ...
</script>

You need to use the child component in the parent like, so:

// inside app.vue
<template>
  <hello :myData='myData'></hello> // I believe this is your objective
</template> //:myData is binding the property from the components data field, without using it, you will get myData as `string` in the child component.

<script>
  export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  }
</script>

OP requested a way to pass in props to a child without rendering the child in the template.

So I am posting a link to the documentation

Vue.component('hello', {
  render: function (createElement) {
    return createElement(
      <tag-names>
    )
  },
  props: {
    myData: parentComponent.myData // you need to give the parent components' data here.
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM