Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在组件方法中等待来自父级的数据_Javascript_Vue.js - Fatal编程技术网

Javascript 如何在组件方法中等待来自父级的数据

Javascript 如何在组件方法中等待来自父级的数据,javascript,vue.js,Javascript,Vue.js,我有一个来自布局的API调用,我想向我的组件发送一个包含API数据的对象 问题是,在mounted()函数中调用方法时,我的对象是空的。因此,只有在API服务上有数据时,我才需要执行此函数 axios.get('/class') .then((response) => { console.log(response.data.results) response.data.results.forEach(element => {

我有一个来自布局的API调用,我想向我的组件发送一个包含API数据的对象

问题是,在
mounted()
函数中调用方法时,我的对象是空的。因此,只有在API服务上有数据时,我才需要执行此函数

axios.get('/class')
    .then((response) => {
        console.log(response.data.results)
        response.data.results.forEach(element => {
            const object = {
                clientId: element.client.objectId,
                price: element.price || 0,
                driverId: element.objectId || null
            }
            this.serviceData.tripsInfo.push(object) // service data is the object will send to the the component
            ...
HTML:

<class title="List of class" :points="serviceData"/>
函数将监视具有相同名称的属性或数据属性,并在其依赖项每次更新时运行相应的函数

props: {
    points: Object
},
watch: {
    points() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        this.totalPrices = this.points.class.map(x => x.price).reduce(reducer)
    }
}
因此,本质上,只要用数据填充
,减速器就会运行

或者,您可以将所有这些压缩为计算属性:

computed: {
    totalPrices: function() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        return this.points.class.map(x => x.price).reduce(reducer)
    }
}

可以使用:
V-if
解决此问题,如:

<class title="" v-if="serviceData.class.length > 0" :points="serviceData"/> 


返回数据时,您可以使用watch函数运行reducer,以及如何执行此操作?这是我第一次用JS填充
tripsInfo
,而不是
class
,我得到了一个错误(“points”属性的默认值类型必须是一个函数),好了,现在什么都没发生,我使用了console.log('test'))在我的watch函数中测试它的执行情况,但我发现该函数并没有像Axios请求那样启动声音。您是否检查了返回的数据并正确设置为
serviceData
?不,我的Axios请求正常,现在我已使用V-if解决了该问题,在执行我的组件之前,watcher应在这种情况下工作。无论哪种方式,如果你能使用
v-if
,那绝对是更好的选择。
<class title="" v-if="serviceData.class.length > 0" :points="serviceData"/>