我从布局中调用了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")
},
答案 0 :(得分:1)
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
一旦填充了数据,reduce器就会运行。
或者,您可以将所有这些压缩为一个计算所得的属性:
computed: {
totalPrices: function() {
const reducer = (accumulator, currentValue) => accumulator + currentValue
return this.points.class.map(x => x.price).reduce(reducer)
}
}
答案 1 :(得分:0)
可以使用:@Document
来解决此问题:
V-if