vue实现接口连接
Vue 实现接口连接的方法
使用 Axios 发送 HTTP 请求
安装 Axios 依赖:
npm install axios
在 Vue 组件中引入并使用 Axios:
import axios from 'axios';
export default {
methods: {
fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
}
}
}
配置全局 Axios 实例
在 main.js 或单独配置文件中设置全局 Axios 默认值:
import axios from 'axios';
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 5000;
Vue.prototype.$http = axios;
使用 async/await 语法
在 Vue 组件方法中使用现代异步语法:
export default {
methods: {
async getData() {
try {
const response = await this.$http.get('/data');
this.data = response.data;
} catch (error) {
this.error = error.message;
}
}
}
}
处理跨域问题
在 vue.config.js 中配置代理:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
封装 API 模块
创建 api.js 集中管理接口:
import axios from 'axios';
export default {
getUsers() {
return axios.get('/users');
},
createUser(data) {
return axios.post('/users', data);
}
}
使用 Vuex 管理接口状态
在 store 中处理异步操作:
const actions = {
async fetchUsers({ commit }) {
try {
const response = await api.getUsers();
commit('SET_USERS', response.data);
} catch (error) {
commit('SET_ERROR', error);
}
}
}
拦截器配置
添加请求和响应拦截器:

axios.interceptors.request.use(config => {
config.headers['X-Requested-With'] = 'XMLHttpRequest';
return config;
});
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
router.push('/login');
}
return Promise.reject(error);
}
);






