赞
踩
在 Vue 2 中集成和使用 Axios 进行 HTTP 请求操作,通常包括以下几个步骤:
在项目目录下通过 npm 或 yarn 安装 Axios。
npm install axios
# 或者
yarn add axios
为了让所有 Vue 组件都能方便地访问 Axios,可以将其挂载到 Vue 的原型上,这样在每个组件中就可以通过 this.$http 来调用 Axios。
在 main.js 文件中进行如下配置:
import axios from 'axios'; import Vue from 'vue'; // 设置默认配置(可选) axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL; // 设置 API 基础 URL // 将 axios 挂载到 Vue.prototype 上 Vue.prototype.$http = axios; // 创建并使用一个自定义实例(可选) const request = axios.create({ headers: {'Content-Type': 'application/json;charset=UTF-8'}, // 其他自定义配置项... }); Vue.prototype.$api = request; // 如果需要区分不同类型的请求,可以创建多个实例并分别挂载 new Vue({ render: h => h(App), }).$mount('#app');
• 发起 GET 请求:
this.$http.get('/api/users')
.then(response => {
console.log(response.data);
// 处理成功回调逻辑
})
.catch(error => {
console.error(error);
// 处理错误回调逻辑
});
发起 POST 请求,并且如果需要发送 JSON 格式的数据:
let data = { name: 'John', age: 30 };
this.$http.post('/api/users', data)
.then(response => {
// ...
})
.catch(error => {
// ...
});
可以设置请求/响应拦截器来处理全局的请求前缀、添加 JWT token 等操作:
axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); // 获取 token 示例 if (token) { config.headers.Authorization = `Bearer ${token}`; // 设置请求头 } return config; }, error => Promise.reject(error)); // 添加响应拦截器 axios.interceptors.response.use(response => { // 对响应数据做统一处理,如错误码判断等 return response; }, error => { // 对响应错误做统一处理,如弹出通知或重定向登录页面 return Promise.reject(error); });
在 Vue 组件的 methods 或其他支持 async 函数的地方,可以结合 async/await 来简化异步操作:
async fetchData() {
try {
const response = await this.$http.get('/api/data');
this.someData = response.data;
} catch (error) {
console.error('Fetch data failed:', error);
}
}
以上就是 Vue 2 中如何使用 Axios 的基本步骤。
根据实际项目需求,还可以进一步封装 Axios 实例以提供更符合业务逻辑的 API 调用方式。
在 Vue.js 中封装 Axios API 可以简化请求处理并提供统一的错误处理、默认配置和数据格式化。以下是一个简单的 Axios 封装示例:
// 创建一个名为 AxiosApi 的文件,例如:Axios.js import axios from 'axios'; // (可选)如果你希望使用 axios 的 CancelToken 来支持取消请求 let cancelTokenSource = null; // 用于取消请求(仅当使用 axios 时) function createCancelToken() { // 如果你选择使用 axios 的 CancelToken 功能 if (axios) { cancelTokenSource = axios.CancelToken.source(); return cancelTokenSource.token; } // 如果不使用 axios,可以忽略这部分 return null; } export default async function AxiosApi(url, options = {}) { const { method = 'GET', body, headers = {}, params, isJson = true } = options; // 添加全局请求头或其他默认配置 headers['Content-Type'] = isJson ? 'application/json' : headers['Content-Type'] || 'text/plain'; // 处理 GET 请求参数 if (method === 'GET' && params) { url = new URL(url, window.location.origin); Object.keys(params).forEach(key => url.searchParams.append(key, params[key])); } // 创建取消请求标记(如果使用 axios) const cancelToken = createCancelToken(); try { const response = await Axios(url, { method, headers, ...(body && { body: isJson ? JSON.stringify(body) : body }), // 对于 POST/PUT 等方法,发送 JSON 格式的数据 ...(cancelToken && { signal: cancelTokenSource.token }), // 如果有取消请求功能,传递信号对象 }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = isJson ? await response.json() : await response.text(); // 根据需要解析响应内容为 JSON 或文本 return { success: true, data, message: '请求成功', }; } catch (error) { // 如果是 Axios 的取消错误,则识别出来 if (axios.isCancel(error)) { console.error('Request canceled', error.message); return { success: false, message: '请求已取消', }; } console.error('Axios API 请求失败', error); return { success: false, message: '服务器异常,请稍后重试', }; } }
然后,在你的 Vue 组件中引入并使用这个封装好的 AxiosApi 函数:
import AxiosApi from './Axios.js'; export default { name: 'MyComponent', methods: { async AxiosData() { const response = await AxiosApi('/api/data', { method: 'GET', params: { id: 1 }, }); if (response.success) { this.data = response.data; } else { // 处理错误 } }, }, mounted() { this.AxiosData(); }, };
以上代码封装了 Axios API 的基本用法,并且提供了一定程度的错误处理和默认配置。你可以根据项目的具体需求对它进行扩展,比如增加拦截器、添加身份验证信息、处理分页等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。