vue.js - 在调用 getter 以通过 id 获取项目时未定义
问题描述
居民.js
state : {
residents: []
},
getters:{
getResidentsById: (state) => (id) => {
return state.residents.find(resident => resident.id === id)
}
}
药物治疗.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)
})
);
},
}
我想通过从药物中传递居民 ID在药物列表中设置residentName道具。我在调用getResidentsById时变得不确定。Medication 对象包含 resident 键,其值为 resident 的 id。
解决方案
// 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。
如果您需要视图上的数组,请为其创建特定的吸气剂。
推荐阅读
- ruby-on-rails - Rails API 帖子不起作用 - csrf?
- php - JQuery .get() 函数未从外部站点检索 PHP 正则表达式回显
- swift - 在 Swift 中使用 DateFormatter 和 TimeZone 来格式化日期
- python - xy绘制python后在matplotlib中绘制标签
- angular - 将令牌作为 http 调用插入标头
- javascript - 如何替换 JQuery 或 Javascript 中的每个单词?
- linux - 如何在linux中复制2个目录仅覆盖bash中的旧文件
- sql-server - while循环内的T-SQL动态sql
- c# - 如何为 3rd 方库类动态创建包装类?
- python - 在 shell 脚本或大查询中创建多个视图