我的函数应该使用来自自身的参数迭代地将JSON插入到特定级别的嵌套JSON的每个元素中,这是复制返回的第一个对象并将其插入到每个嵌套参数中。请参阅下面的屏幕截图和代码,了解我正在做的事情。
基本上我在状态中有一个嵌套的JSON对象,并且需要迭代地追加到每个'行的嵌套属性。现有对象使用从API返回JSON的操作,然后是更新状态的突变。
问题在于我认为的突变。我推断我的功能是复制从API返回的第一个JSON对象。请参阅下面的Action和Mutation函数,以及JSON的API函数和结构。
http://api.capecodcommission.org/docs/index.html#sumofannualcapitaltotalsfortreatment
使用v-for运行的特定组件中的函数:
methods: {
costTotal () {
return this.updateFinTotals(this.treatment.treatmentId,this.costType.treatTotal,this.costType.financeOption,this.treatment.relativeStartYear,this.costType.finDur,this.costType.prinFor)
}
}
运行功能,查看JSON:
<td class="text-center">
{{ costTotal }}
{{ costType.annualized.sumOfAnnualCapitalTotals }}
</td>
V-for Loop:
<tbody>
<tr v-for="(index, costType) in treatment.costTypes | filterBy 'true' in 'financeable'" is="cost-type-table-row-finance" :cost-type="costType"></tr>
</tbody>
API函数:
getSumOfAnnualCapitalTotals (treatmentId, costToFinance, financeOption, relativeStartYear, financeDuration, principalForgivenessRate) {
let data = {
treatmentId: treatmentId,
costToFinance: costToFinance,
financeOption: financeOption,
relativeStartYear: relativeStartYear,
financeDuration: financeDuration,
principalForgivenessRate: principalForgivenessRate
}
return Vue.http.post(API_ROOT + 'sumOfAnnualCapitalTotalsForTreatment', data)
}
操作:从API中提取JSON,调度突变功能。
export const updateFinTotals = function ({ dispatch, state }, treatmentId, costToFinance, financeOption, relativeStartYear, financeDuration, principalForgivenessRate) {
api.getSumOfAnnualCapitalTotals( treatmentId, costToFinance, financeOption, relativeStartYear, financeDuration, principalForgivenessRate ).then(function (response) {
dispatch('UPDATE_ANNUALIZED', response.data)
}, function (response) {
console.log(response)
})
}
Mutation:使用JSON更新状态。
UPDATE_ANNUALIZED (state, annualized) {
for (var i = 0; i < state.scenario.treatments.length; i++) {
for (var j = 0; j < state.scenario.treatments[i].costTypes.length; j++) {
state.scenario.treatments[i].costTypes[j]["annualized"] = annualized
}
}
}
编辑:下面的PICS
答案 0 :(得分:0)
好吧,您的API会返回一个值(一个 一个处理的成本类型
)链接API文档的示例:
{"sumOfAnnualCapitalTotals":150374.9849625}
但您使用突变中的for循环将其分配给所有成本类型的所有处理:
for (var i = 0; i < state.scenario.treatments.length; i++) {
for (var j = 0; j < state.scenario.treatments[i].costTypes.length; j++) {
state.scenario.treatments[i].costTypes[j]["annualized"] = annualized
}
}
你应该做的是将treatmentID
和费用类型(我,sherlock-holmed,称为costToFinance
)从操作传递到变异,然后过滤匹配对象的状态,并仅更新:
UPDATE_ANNUALIZED (state, treadmentId, costToFinance, annualized) {
const treatment = state.treatments.find((t) => t.treatmentId === treatmentId)
const currCostType = treatment.costTypes.find((costType) => costType.Id === costToFinance)
currCostType.annualized = annualized
}
问题是你的JSON似乎没有任何关于costTypes的ID到find
它,但那是你要弄明白的。