对于我国家列表中的每个国家,我需要使用axios进行api调用以获取另一个值,这里是y组件:
<div class="my-table-component">
<div class="my-table-component-header">
<div class="my-table-component-header-item" *ngFor="let header of columnHeaders">
<ng-container *ngTemplateOutlet="header; context: {$implicit:Item}"></ng-container>
</div>
</div>
<div class="my-table-component-content" *ngFor="let Item of Items">
<div class="my-table-component-content-item" *ngFor="let cell of columnCells">
<ng-container *ngTemplateOutlet="cell; context: {$implicit: Item}"></ng-container>
</div>
</div>
</div>
在我的脚本中,我调用已安装的方法matchCount并将其值存储在县数据对象中:
<template>
<div>
<div v-for="(country, i) in countries" :key="i">
<div>{{ county[i.id].count }}</div>
</div>
</div>
</template>
我收到此错误“ TypeError:无法读取未定义的属性'count'”,我应该如何调用此方法?
答案 0 :(得分:2)
在HTML模板{{variable[key] && variable[key].value}}
中,使用以下语法会发现有用。
在您的情况下,应该是:
<template>
<div>
<div v-for="(country, i) in countries" :key="i">
<div>{{ county[i.id] && county[i.id].count }}</div>
</div>
</div>
</template>
它的作用实质上是验证键i.id
是否存在于county
数组中。如果没有,它将不会引发有关丢失对象/键的错误。
在使用对象时也可以使用以下语法:
<div v-text="house.dog && house.dog.name" ></div>
如果dog
在house
对象中,它将显示dog's
的名称。
编辑:
在函数中添加this.$forceUpdate();
:
matchCount() {
var paysCount = this.pays;
paysCount.forEach(item => {
this.$axios
.get(
`https://api.com/federation/}/${item.id}/`
)
.then(response => {
this.county[item.id] = {};
this.county[item.id].count = response.data.length.toString();
this.$forceUpdate();
});
});
}
答案 1 :(得分:1)
county[item.id].count
是异步设置的,在呈现组件时它可能不可用。您可以添加安全检查:
<template>
<div>
<div v-for="(country, i) in countries" :key="i">
<div v-if="county[i.id]">{{ county[i.id].count }}</div>
<div v-else>Loading...</div>
</div>
</div>
</template>
似乎您有reactivity problem:
this.$axios
.get(
`https://api.com/federation/}/${item.id}/`
)
.then(response => {
this.$set(this.county, item.id, {count: response.data.length.toString())
});