vue 实现接口调用
使用 Axios 进行接口调用
安装 Axios 依赖:
npm install axios
在 Vue 组件中引入 Axios:
import axios from 'axios';
发送 GET 请求示例:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
发送 POST 请求示例:
axios.post('https://api.example.com/data', { key: 'value' })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
配置全局 Axios 实例
创建全局配置:
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
设置请求拦截器:

instance.interceptors.request.use(
config => {
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);
}
);
使用 async/await 语法
在 methods 中使用 async/await:
methods: {
async fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
}
处理跨域问题
配置 vue.config.js 开发环境代理:

module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
封装 API 模块
创建 api.js 文件:
import axios from 'axios';
const api = {
getUser(id) {
return axios.get(`/users/${id}`);
},
createUser(data) {
return axios.post('/users', data);
}
};
export default api;
在组件中使用:
import api from './api';
export default {
methods: {
async loadUser() {
const user = await api.getUser(1);
console.log(user);
}
}
}
处理加载状态
在组件中添加 loading 状态:
data() {
return {
isLoading: false,
data: null
};
},
methods: {
async fetchData() {
this.isLoading = true;
try {
const response = await axios.get('/api/data');
this.data = response.data;
} finally {
this.isLoading = false;
}
}
}
错误处理最佳实践
统一错误处理方式:
async fetchData() {
try {
const response = await axios.get('/api/data');
return response.data;
} catch (error) {
if (error.response) {
// 服务器返回错误状态码
console.log(error.response.status);
} else if (error.request) {
// 请求已发出但无响应
console.log('No response received');
} else {
// 其他错误
console.log('Error', error.message);
}
throw error;
}
}






