【发布时间】:2020-01-27 17:33:42
【问题描述】:
我想使用 getter 在数据中设置字段:
export default {
data () {
return {
medications: [],
}
},
computed: {
...mapGetters([
'allMedications',
'getResidentsById',
]),
我想设置medications = allMedications,我知道我们可以使用{{allMedications}},但我的问题是假设我有:
medications {
name: '',
resident: '', this contains id
.......
}
现在我想致电 getResidentsById 并在 medications 上设置一个额外字段:
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
},
}
但这似乎有问题,因为只有当 allMedications 发生变化时,watch 上的方法才会激活并设置 residentName。 p>
【问题讨论】:
标签: vue.js vuejs2 vue-component vuex