You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:25:56