Extension of the Axios library for use with Vue.js. The main purpose is to integrate a loading indicator (using Vue's Ref type) with Axios requests to automatically change state of loading state.
Check the example project
- Create or insert into existing
env.d.ts
file located on the same directory withtsconfig.json
. If you don't use typescript in your project, skip
import 'axios';
import type { Ref } from 'vue';
declare module 'axios' {
interface AxiosRequestConfig {
isLoading?: Ref<boolean>;
}
}
- Create file to initialize instance of axios. In my case it is
utils.ts
import axios from 'axios'
const instance = axios.create({});
const updateLoadingStatus = (config: any, status: boolean) => {
if (config.isLoading)
config.isLoading.value = status
};
instance.interceptors.request.use((config) => {
updateLoadingStatus(config, true);
return config;
});
instance.interceptors.response.use(
(response) => {
updateLoadingStatus(response.config, false);
return response;
},
(error) => {
if (error.response) {
updateLoadingStatus(error.response.config, false);
} else if (error.config) {
updateLoadingStatus(error.config, false);
}
return Promise.reject(error);
}
);
export default instance as typeof axios;
- Use axios and include reactive variable when requesting. Look at the example:
<script lang="ts" setup>
import {ref} from "vue";
import axios from "./utils";
const isLoading = ref(false);
function get() {
axios.get("https://jsonplaceholder.typicode.com/todos/1", {
isLoading: isLoading
}).then(async (response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
});
}
</script>
<template>
<header>
<h1>Axios Reactivity Example</h1>
</header>
<main>
<button @click="get" :disabled="isLoading">Get</button>
</main>
</template>