Vue 中 Axios 配置指南

Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js 环境。在 Vue 项目中,Axios 常用于与后端 API 进行通信。本文将介绍如何在 Vue 项目中配置和使用 Axios。

一、安装 Axios

首先,你需要在 Vue 项目中安装 Axios。通过 npm 或 yarn 安装:

 
npm install axios --save
# 或
yarn add axios

二、全局配置 Axios

在 Vue 项目中,你可以在项目的入口文件(如 main.js)中进行 Axios 的全局配置。这样,在整个项目中都可以使用这个配置。

 
import Vue from 'vue';
import axios from 'axios';

// 创建 axios 实例
const instance = axios.create({
baseURL: 'https://api.example.com', // 设置基础 URL
timeout: 5000, // 设置请求超时时间
headers: {
'Content-Type': 'application/json'
}
});

// 请求拦截器
instance.interceptors.request.use(config => {
// 在发送请求之前做些什么,例如添加 token
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
}, error => {
// 对请求错误做些什么
return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use(response => {
// 对响应数据做点什么
return response.data;
}, error => {
// 对响应错误做点什么
return Promise.reject(error);
});

// 将 axios 实例挂载到 Vue 原型上
Vue.prototype.$axios = instance;

new Vue({
render: h => h(App)
}).$mount('#app');

三、在组件中使用 Axios

在 Vue 组件中,你可以通过 this.$axios 访问全局配置的 Axios 实例,发起 HTTP 请求。

 
<template>
<div>
<h1>用户列表</h1>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>

<script>
export default {
data() {
return {
users: []
};
},
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const response = await this.$axios.get('/users');
this.users = response.data;
} catch (error) {
console.error('获取用户列表失败:', error);
}
}
}
};
</script>

四、局部配置 Axios

如果你只想在某个组件中使用 Axios,而不是全局配置,可以在组件内部直接引入 Axios 并创建实例。

 

<template>
<div>
<h1>用户详情</h1>
<p>{{ user.name }}</p>
</div>
</template>

<script>
import axios from 'axios';

export default {
data() {
return {
user: {}
};
},
created() {
this.fetchUser();
},
methods: {
async fetchUser() {
try {
const response = await axios.get('https://api.example.com/users/1');
this.user = response.data;
} catch (error) {
console.error('获取用户详情失败:', error);
}
}
}
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值