
在 Vue.js 项目中使用 Axios 获取 API 数据时,经常会遇到控制台输出 undefined 的情况,导致页面无法正确渲染。以下面代码为例,问题可能出现在多个环节:
export interface TestResponse {
firtName: string
lastName: string
}
export interface TestResponseRO {
data: TestResponse[]
metadata: string
}const request: AxiosInstance = axios.create({
baseURL: url.baseUrl,
headers: {
'content-type': 'application/json',
},
//params: {base64_encoded: 'true', fields: 'stdout'},
});
export const api = {
async getTest() {
try{
return await request.get<TestResponse>("/v1/test")
.then(res => {
console.log("lastname " + res.data.lastName);
return res.data
})
}catch (err) {
console.log("error" + err);
}
},
}export default {
name: "Test",
setup() {
const firstName = ref('');
const lastName = ref('');
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
firstName.value = response[0].data.firstName
lastName.value = response[0].data.lastName
console.log("I am a name " + response.lastName)
}
} catch (error) {
console.log('Error while getting the response:', error)
}
}
return {
firstName,
lastName,
submit
}
},
};首先,要确保 TypeScript 类型定义与 API 返回的数据结构完全匹配。根据提供的 JSON 响应示例:
{
"data": [
{
"firstName": "Foo",
"lastName": "Smith"
},
{
"firstName": "Mike",
"lastName": "vue"
},
{
"firstName": "go",
"lastName": "lang"
}
],
"metadata": "none"
}正确的 TypeScript 类型定义应如下所示:
export interface TestResponse {
firstName: string;
lastName: string;
}
export interface TestResponseRO {
data: TestResponse[];
metadata: string;
}注意:
立即学习“前端免费学习笔记(深入)”;
其次,需要优化 Axios 请求的处理方式。使用 async/await 语法时,无需再使用 .then() 方法。正确的写法如下:
import axios, { AxiosInstance } from 'axios';
const request: AxiosInstance = axios.create({
baseURL: url.baseUrl,
headers: {
'content-type': 'application/json',
},
//params: {base64_encoded: 'true', fields: 'stdout'},
});
export const api = {
async getTest() {
try {
const res = await request.get<TestResponseRO>("/v1/test");
console.log(res.data) // Should display '{"data": [your array], "metadata": "none"}'
return res.data;
} catch (err) {
console.error(err);
return null; // 建议返回 null 或抛出异常,以便在调用方处理错误
}
},
}关键点:
最后,在 Vue 组件中,需要根据 API 返回的数据结构正确访问数据。
import { ref } from 'vue';
import api from './api'; // 假设 api 对象在单独的文件中
export default {
name: "Test",
setup() {
const firstName = ref('');
const lastName = ref('');
const submit = async () => {
try {
const response = await api.getTest();
if (response != null && response.data && response.data.length > 0) {
firstName.value = response.data[0].firstName;
lastName.value = response.data[0].lastName;
console.log("First Name: " + firstName.value);
console.log("Last Name: " + lastName.value);
} else {
console.warn("No data received from API.");
}
} catch (error) {
console.error('Error while getting the response:', error);
}
}
return {
firstName,
lastName,
submit
}
},
};关键点:
通过以上步骤,可以有效地排查和解决 Vue.js 项目中使用 Axios 获取 API 数据时出现 undefined 错误的问题,确保数据正确渲染,提升用户体验。
以上就是Vue.js 中 Axios 请求返回 Undefined 的问题排查与解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号