1. 建立hook文件夹,在hook文件夹里面建立 useAxios.ts 文件,内容如下:
import { ref } from 'vue';
import axios from 'axios';
export default function<T>(url: string, method: string, param?: object) {
const loading = ref(true);
const data = ref<T | null>(null);
const errorMsg = ref('');
if (method === 'get') {
axios.get(url).then(res => {
loading.value = false;
data.value = res.data;
}).catch(err => {
loading.value = false;
errorMsg.value = err.message || '未知错误';
})
}
if (method === 'post') {
axios.post(url, param).then(res => {
loading.value = false;
data.value = res.data;
}).catch(err => {
loading.value = false;
errorMsg.value = err.message || '未知错误';
})
}
return {
loading,
data,
errorMsg
}
}
2. 在组件中使用
<script lang='ts'>
import { defineComponent } from 'vue'
import useAxios from './useAxios'
interface dataProps {
n?: number,
total?: number,
money?: number
}
export default defineComponent ({
setup() {
const {loading, data, errorMsg} = useAxios<dataProps[]>('/myUrl/id=1','get')
return {
loading,
data,
errorMsg
}
},
})
</script>