// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';
import { setupAxios } from './utils/api';
const app = createApp(App);
setupAxios(axios);
app.mount('#app');
您可以在utils/api.ts文件中添加其他HTTP方法和相应的参数,例如:
// utils/api.ts
import axios, { AxiosInstance } from 'axios';
export let $axios: AxiosInstance;
export function setupAxios(axiosInstance: AxiosInstance) {
$axios = axiosInstance;
}
export function post(url: string, data: any) {
return $axios.post(url, data);
}
export function get(url: string) {
return $axios.get(url);
}
export function put(url: string, data: any) {
return $axios.put(url, data);
}
export function del(url: string) {
return $axios.delete(url);
}
您可以在其他地方使用封装好的API函数:
// Example.vue
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { post } from './utils/api';
export default defineComponent({
setup() {
const response = ref('');
const handleSubmit = async () => {
const res = await post('https://example.com/api', { name: 'John Doe' });
response.value = res.data;
};
return {
response,
handleSubmit,
};
},
});
</script>
此示例中的API函数只是基本的封装示例,您可以根据您的需求修改和定制。