1
votes

I am new to Vue and I am trying to get parent's component data with props from a child component but got an undefined error when I do console.log().

Parent:

import axios from 'axios'
import PieChart from './components/PieChart'

export default {
  data () {
    return {
      requires: [],
      tested: [],
      requires_php: [],
      errors: [],
      url: 'https://api.miruc.co/plugins.min.json'
    }
  },
  created: function () {
    axios.get(this.url)
    .then(response => {
      this.requires = response.data[0]
      this.tested = response.data[1]
      this.requires_php = response.data[2]
    })
    .catch(e => {
      this.errors.push(e)
    })
  },
  components: {
    'pie-chart': PieChart
  }
}

Child:

export default {
  extends: Pie,
  props: ['req'],
  mounted: function () {
    console.log(this.req)
    /*  */
  }
}

Can anyone tell me what mistake I am doing?

2
I would guess that the http get is still running by the time your console.log is reached. - Richard Matsen
@RichardMatsen I tried with setTimeout(function () { alert(this.req) }, 10000) but I still get the same error. Even the Vue extenstion on Chrome says it's undefined. - mirucon
You can find out for sure by putting another console.log in the .then(response => { method and see what order they appear in. - Richard Matsen
I got undefined there... it's weird, Vue extension says it stores an object. - mirucon
Ok, I didn't expect that. 'Vue extension' - what's that? - Richard Matsen

2 Answers

2
votes

You need to pass props to a child-component within the parents template, e.g:

<template>
//...
    <pie-chart :req="requires"></pie-chart>
//...
</template>
0
votes

I do not know what you did with your template codes. But see what happens when you change your Parent's code like this:

import axios from 'axios'
import PieChart from './components/PieChart'

export default {
  data () {
    return {
      requires: [],
      tested: [],
      requires_php: [],
      errors: [],
      url: 'https://api.miruc.co/plugins.min.json'
    }
  },
  created: function () {
    axios.get(this.url)
    .then(response => {
      Vue.set(this, 'requires', response.data[0])
      Vue.set(this, 'tested', response.data[1])
      Vue.set(this, 'requires_php', response.data[2])
    })
    .catch(e => {
      this.errors.push(e)
    })
  },
  components: {
    'pie-chart': PieChart
  }
}

One thing to remember: whenever you set an array or object elements always use Vue.set. It assures reactivity for the inner elements.