1. 安装 Axios
首先,确保你的项目中已经安装了 Axios。如果尚未安装,可以通过 npm 或 yarn 来安装它:
npm install axios
或者
yarn add axios
2. 创建 Axios 实例
在 Vue 3 项目中,通常建议在项目的某个模块或服务文件中创建一个 Axios 实例,以便在需要时可以轻松地重用和配置它。例如,你可以在 src/utils 或 src/services 目录下创建一个 axios.js 文件:
// src/utils/axios.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com', // 你的 API 基础 URL
timeout: 1000, // 请求超时时间
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN_HERE' // 根据需要添加认证头
}
});
export default api;
3. 在 Vue 组件中使用 Axios 实例
然后,在你的 Vue 组件中,你可以通过导入你创建的 Axios 实例来使用它:
// 在 Vue 组件中
<script setup>
import api from '@/utils/axios';
const fetchData = async () => {
try {
const response = await api.get('/data'); // 发送 GET 请求到 /data 端点
console.log(response.data); // 处理响应数据
} catch (error) {
console.error('There was an error!', error); // 处理错误
}
};
</script>
4. 全局错误处理和请求拦截器(可选)
如果你想要全局地处理错误或者添加请求拦截器,你可以在创建 Axios 实例后进行设置:
// src/utils/axios.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {}
});
// 添加请求拦截器
api.interceptors.request.use(function (config) {
// 在发送请求之前做些什么,例如设置认证头等
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
api.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么,例如统一处理错误状态码等
if (error.response && error.response.status === 401) { // 例如,处理401未授权错误
// 重定向到登录页面等操作...
}
return Promise.reject(error);
});
export default api;
5. 使用 Composition API 或 Options API(根据需要)
Vue 3 支持 Composition API 和 Options API。上面的示例使用了 Composition API 的 <script setup> 语法糖。如果你更喜欢使用 Options API,可以这样写:
<script>
import api from '@/utils/axios';
export default {
name: 'YourComponent',
methods: {
async fetchData() {
try {
const response = await api.get('/data'); // 发送 GET 请求到 /data 端点
console.log(response.data); // 处理响应数据
} catch (error) {
console.error('There was an error!', error); // 处理错误
}
}
}
};
</script>