首页 > 解决方案 > 在调用 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。

标签: vue.jsvuejs2vuex

解决方案


// 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。

如果您需要视图上的数组,请为其创建特定的吸气剂。


推荐阅读