vue项目ts调用axios的方法
时间: 2023-06-02 11:04:39 浏览: 110
我可以回答这个问题。如果您在Vue项目中使用TypeScript,您需要为axios创建一个类型接口并将其导入到您的组件中。然后,您可以使用async/await或.then()来调用axios并处理返回的数据。以下是一些示例代码:
在.d.ts文件中创建axios类型接口:
```
import { AxiosRequestConfig, AxiosResponse } from 'axios';
export interface AxiosInstance {
request<T = any, R = AxiosResponse<T>>(config: AxiosRequestConfig): Promise<R>;
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
}
```
在组件中导入axios和axios的类型接口:
```
import axios, { AxiosInstance } from 'axios';
import { AxiosInstance as MyAxiosInstance } from '@/types/axios';
export default Vue.extend({
data() {
return {
responseData: [],
};
},
methods: {
async fetchData() {
try {
const response = await (this.$axios as MyAxiosInstance).get('/api/data');
this.responseData = response.data;
} catch (error) {
console.error(error);
}
},
},
});
```
阅读全文