// src/http.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
class AxiosHttp {
private instance: AxiosInstance;
constructor() {
this.instance = axios.create({
baseURL: 'https://api.example.com', // 请替换为你的 API 基础 URL
timeout: 10000, // 请求超时时间
headers: {
'Content-Type': 'application/json'
}
});
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
return config;
},
(error) => {
return Promise.reject(error);
}
);
this.instance.interceptors.response.use(
(response: AxiosResponse) => {
return response.data;
},
(error) => {
return Promise.reject(error);
}
);
}
public get<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
return this.instance.get<T>(url, { ...config, params });
}
public post<T>(url: string, data: any, config?: AxiosRequestConfig): Promise<T> {
return this.instance.post<T>(url, data, config);
}
// 你可以根据需要继续添加其他请求方法
}
export default new AxiosHttp();
// src/api.ts
import AxiosHttp from './http';
interface GetUserParams {
id: number;
name?: string;
}
export const getUser = (params: GetUserParams) => {
return AxiosHttp.get<any>('/user', params);
};
export const getPosts = (params: { userId: number }) => {
return AxiosHttp.get<any[]>('/posts', params);
};
// 你可以根据需要添加更多的 API 方法
// src**加粗样式**/components/MyComponent.vue
<template>
<div>
<h1>Data</h1>
<pre>{{ data }}</pre>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { getUser } from '../api';
export default defineComponent({
data() {
return {
data: null
};
},
async mounted() {
try {
const params = { id: 1, name: 'John' }; // 你要传递的参数
const response = await getUser(params);
this.data = response;
} catch (error) {
console.error('Error fetching data:', error);
}
}
});
</script>