调用 getter 通过 id 获取项目时未定义
2020-01-25
207
resident.js
state : {
residents: []
},
getters:{
getResidentsById: (state) => (id) => {
return state.residents.find(resident => resident.id === id)
}
>
Medication.vue
data() {
return { medications: [],
},
computed: {
...mapGetters([
'allMedications', //this returns all the list of medication
'getResidentsById',
]),
},
method: {
getResidentName(id) {
const resident = this.getResidentsById(id)
return resident && resident.name
},
},
watch: {
allMedications() {
const medicationArray = this.allMedications
this.medications = medicationArray.map(medication =>
({
...medication,
residentName: this.getResidentName(medication.resident)
})
);
},
}
我想通过从 medication 传递 resident id 来设置 medications 列表中的 residentName 属性。我在调用 getResidentsById 时得到 undefined 。Medication 对象包含 resident 键,其值为 resident 的 id。
1个回答
// residents.js
import Vue from 'vue'
const state = {
residents: {}
}
const mutations = {
RESIDENT_ADD (state, value) {
Vue.set(state.residents, value.residentId, value)
}
}
const actions = {
}
const getters = {
getResidents: state => {
const arr = []
for (const key in state.residents) {
const obj = state.residents[key]
arr.push(obj)
}
return arr
},
getResidentById: state => id => {
const obj = state.residents[id] ? state.residents[id] : null
return obj
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
这应该可以解决问题。
顺便说一句,避免在状态中使用数组,因为如果您从数组中删除或添加项目,它会触发很多 getter。
如果您需要视图上的数组,请为其创建一个特定的 getter。
Johnny
2020-03-06