Vue props undefined

Vue props undefined

问题描述:

我是Vue的新手,我试图从一个子组件获取父组件的数据,但是当我使用console.log()的时候出现了未定义的错误。Vue props undefined

家长:

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

儿童:

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

谁能告诉我我在做什么错误?

+0

我猜测,到达console.log时,http get仍然在运行。 –

+0

@RichardMatsen我尝试'setTimeout(function(){alert(this.req)},10000)'但我仍然得到相同的错误。即使是Chrome上的Vue扩展,它也没有定义。 – Flexi

+0

你可以通过在'.then(response => {'方法,看看它们出现在什么顺序中)来安装另一个console.log。 –

您需要家长模板中的道具传递给孩子组分,e.g:

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

它的工作!谢谢。 – Flexi

我不知道你和你的模板代码做了什么。不过看到当你改变你这样的家长的代码会发生什么:

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

有一点要记住:当你设置一个数组或对象的元素总是使用Vue.set。它确保内部元素的反应性。