javascript - 如何在组件方法中等待来自父级的数据
问题描述
我有一个来自布局的 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")
},
解决方案
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)
}
}
推荐阅读
- html - 将十字 png 居中到 css 网格中
- autodesk-forge - 基于属性的动态元素着色
- python - 由于numpy中的and语句导致的ValueError
- php - “!--”自动添加到
我在我的 Linux VM 上完成了一个项目并将其推送到 github 存储库,以便我的同事可以设置另一个 VM 来托管它。我的代码虽然丑陋,但可以正常工作,但是当它托管在 VM 上时,代码就坏了。过了一会儿,我发现我的代码中的 php 标记不知何故从
<?php
to变成了 to ,<!--?php
并将我的代码的- python - 如何在一个列上组合两个数据框,其中一个缺少行?
- javascript - 如何获取页面加载时不包含所有元素的资源(使用 React)?
- c# - IConfiguration(在返回值之前替换占位符标签)
- powerbi - Dax - 每个月的累计总数(日期表有问题)
- html - 浮动在一个 div 中的三个 div 的垂直对齐
- javascript - React JS 映射数据提取