Vue.js 3如何使用Axios调用API获取输入框指定国家的对应数据
Vue3 疫情数据搜索功能修复方案
核心问题说明
- 你当前用
res.data.Turkey.All是静态访问对象属性,要使用变量作为属性名时,必须用JS的方括号动态属性语法:res.data[变量名],这是控制台返回undefined的核心原因 - 仅在组件挂载时请求了一次土耳其的固定数据,没有监听搜索输入的变化来更新对应国家的数据
- 代码中额外引入了Vue2的CDN,会和Vue3框架冲突,需要删除
修正后完整代码
<template> <div> <input type="search" v-model="searchedCountry" placeholder="Search country" /> <!-- 数据展示区域 --> <div v-if="currentCountryData"> <p>累计确诊:{{ currentCountryData.confirmed }}</p> <p>累计死亡:{{ currentCountryData.deaths }}</p> <p>累计康复:{{ currentCountryData.recovered }}</p> </div> <p v-else-if="searchedCountry">未找到对应国家的数据,请检查国家名拼写</p> </div> </template> <script> import axios from 'axios'; import { ref, onMounted, watch} from 'vue'; export default { setup() { // 存储接口返回的所有国家全量数据 const allCountryData = ref({}); // 存储当前搜索到的国家数据 const currentCountryData = ref(null); // 搜索绑定变量 let searchedCountry = ref(''); // 组件挂载时拉取全量数据 onMounted(() => { axios.get('https://covid-api.mmediagroup.fr/v1/cases').then((res) => { allCountryData.value = res.data; }); }); // 监听搜索输入变化,自动匹配对应国家数据 watch(searchedCountry, (newVal) => { if (!newVal) { currentCountryData.value = null; return; } // 动态访问对应国家数据,可选:把输入首字母转大写适配接口字段 const formatCountry = newVal.trim().replace(/^\S/, s => s.toUpperCase()); currentCountryData.value = allCountryData.value[formatCountry]?.All || null; }) return { currentCountryData, searchedCountry, }; }, }; </script>
优化说明
- 接口一次返回全量国家数据,无需每次搜索都发起请求,减少网络开销
- 增加了输入内容首字母大写适配逻辑,不需要用户严格匹配大小写输入
- 增加了不存在国家的兜底提示,避免控制台报错
内容的提问来源于stack exchange,提问作者beste
相关产品推荐
相关产品推荐

