首页 > 解决方案 > 如何在组件方法中等待来自父级的数据

问题描述

我有一个来自布局的 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"/>

class零件:

props: {
    points: {} // here is the layout data
},
mounted () {
    console.log(this.points)
    const reducer = (accumulator, currentValue) => accumulator + currentValue
    this.totalPrices = this.points.class.map(x => x.price).reduce(reducer) // here I got a problem (Reduce of empty array with no initial value")
},

标签: javascriptvue.js

解决方案


watcher函数将监视具有相同名称的任何 prop 或 data 属性,并在每次其依赖项更新时运行相应的函数。

props: {
    points: Object
},
watch: {
    points() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        this.totalPrices = this.points.class.map(x => x.price).reduce(reducer)
    }
}

因此,本质上,一旦points填充了数据,reducer 就会运行。

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

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

推荐阅读