面试题答案
一键面试在Vue项目中使用Axios发送GET请求获取用户列表数据的代码如下:
<template>
<div>
<ul>
<li v-for="user in userList" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
userList: []
};
},
mounted() {
this.fetchUserList();
},
methods: {
fetchUserList() {
axios.get('/api/users')
.then(response => {
this.userList = response.data;
console.log('请求成功,用户列表数据:', this.userList);
})
.catch(error => {
console.error('请求失败:', error);
});
}
}
};
</script>
代码说明
- 引入Axios:在Vue组件中通过
import axios from 'axios';
引入Axios库。 - 数据定义:在
data
函数中定义一个userList
数组,用于存储从API获取到的用户列表数据。 - 生命周期钩子:在
mounted
钩子函数中调用fetchUserList
方法,这样在组件挂载到DOM后就会自动发送请求。 - 发送请求:在
fetchUserList
方法中,使用axios.get('/api/users')
发送GET请求到/api/users
。 - 处理响应:
- 请求成功:通过
.then
回调函数处理成功的响应,将响应数据(response.data
)赋值给userList
,并在控制台打印成功信息。 - 请求失败:通过
.catch
回调函数处理失败的情况,在控制台打印错误信息。
- 请求成功:通过
这样就实现了在Vue项目中使用Axios发送GET请求获取用户列表数据,并处理了请求成功和失败的情况。