我有一个 json 响应,在"产品"中我有"资金",在基金内部我有一个日期字段。 我想在模板中查看日期。
我使用 forEach 迭代产品,然后迭代资金,然后将日期分配给变量。这是在 computed(( 中完成的。
现在我想在模板中获取日期。但我无法取到它。
我尝试在method((中添加相同的方法,但没有成功
data: function(){
return {
date: ''
}
},
computed: {
products: function(){
let products = this.sortedSchemeData.products;
var year = this.selectedSchemeYear;
products.forEach(function(product){
product.funds.forEach(function(fund){
var date = fund.fundsProcessDate;
console.log(date); //some date from json
})
});
return products;
}
},
<template>
<div>
<p>date: <b>{{date}}</b></p>
</template>
date: date in json
当
第一个product
为空时,products[0].funds[0].fundProcessDate
不处理这种情况。我下面的例子确实可以处理它。
computed: {
date() {
const found = this.products.find(product =>
product.funds.some(fund => fund.fundsProcessDate != null)
);
return (found && found.funds[0].fundsProcessDate) || "01-01-2019"; //default date if not found from all of them
}
}
对于此方案,可以使用计算资源库。
data: function(){
return {
date: ''
}
},
computed: {
products: {
// setter
set: function (newValue) {
let products = newValue;
var year = this.selectedSchemeYear;
products.forEach(function(product){
product.funds.forEach(function(fund){
this.date = fund.fundsProcessDate;
})
});
}
}
},
<template>
<div>
<p>date: <b>{{date}}</b></p>
</template>