从getter设置数据字段并添加额外的计算字段



我想使用 getter 在数据中设置字段:

export default {
data () {
return {
medications: [],
}
},
computed: {
...mapGetters([
'allMedications',
'getResidentsById',
]),

我想设置medications = allMedications,我知道我们可以用户{{allMedications}}但我的问题假设我有:

medications {
name: '',
resident: '', this contains id
.......
}

现在我想打电话给getResidentsById,并在药物上设置一个额外的字段:

medications {
name: '',
resident: '', this contains id
residentName:'' add an extra computed field
.......
}

我这样做了:

watch: {
allMedications() {
// this.medications = this.allMedications
const medicationArray = this.allMedications
this.medications = medicationArray.map(medication => 
({
...medication,
residentName: this.getResidentName(medication.resident)
})
);
},
},
method: {
getResidentName(id) {
const resident = this.getResidentsById(id)
return resident && resident.fullName
},
}

但这似乎是有问题的,因为只有当所有药物发生变化时,手表上的方法才会激活并设置居民名称

在这种情况下,您希望在创建组件后立即运行观察程序。您可以在方法中移动逻辑,然后从观察程序和创建的钩子中调用它,但有一种更简单的方法。

您可以使用观察程序的长手版本来传递immediate: true选项。这将使它在解析计算属性后立即运行。

watch: {
allMedications: {
handler: function (val) {
this.medications = val.map(medication => ({
...medication,
residentName: this.getResidentName(medication.resident)
});
},
immediate: true
}
}

最新更新