Vue.js通过Location ID获取对应Location Name出错求助
Vue.js中通过Location ID获取对应Location Name不匹配的解决方法
问题描述
我正在尝试使用Vue.js通过Location ID获取对应的Location Name。当我选择地点时,希望同时获取地点名称,但目前获取的名称与ID不匹配。
相关代码
locationList.vue
<template> <div class="q-gutter-md q-pa-sm col-md-3"> <q-select v-model="location_id" filled label="Locations" :options="api.locations" bg-color="white" name="location_id" dense emit-value map-options option-label="name" option-value="id" @update:model-value="addLocation" /> </div> </template>
脚本部分
methods: { getLocations () { axios.get(process.env.API_URL + '/lookups/locations') .then(({ data: { items } }) => { this.api.locations = items }) .catch((error) => { console.log(error) }) }, addLocation () { let locationName = null if (this.location_id != null) { locationName = this.api.locations.name } store.dispatch('location/storeLocation', { location_id: this.location_id, locations: locationName }) } }
问题根源
this.api.locations是数组类型,直接访问.name无法定位到与选中location_id对应的项,只会得到undefined或错误值。
解决方案
修改addLocation方法,通过Array.find()根据location_id在数组中查找对应项,再提取名称:
methods: { getLocations () { axios.get(process.env.API_URL + '/lookups/locations') .then(({ data: { items } }) => { this.api.locations = items }) .catch((error) => { console.log(error) }) }, addLocation () { let locationName = null if (this.location_id != null) { // 根据location_id查找对应的地点对象 const selectedLocation = this.api.locations.find(location => location.id === this.location_id) // 如果找到对象,取出name,否则保持null locationName = selectedLocation?.name || null } store.dispatch('location/storeLocation', { location_id: this.location_id, locations: locationName }) } }
关键说明
- 使用
Array.find()遍历api.locations数组,匹配id与当前选中的location_id的项 - 可选链操作符
?.避免因找不到对应项而抛出错误,确保代码更健壮 - 最终传递给store的
locations参数将准确对应选中地点的名称
内容的提问来源于stack exchange,提问作者Malik Zubair Mukhtar
相关产品推荐
相关产品推荐

