1. Overview
In this article, we will learn to use Axios in Vue 3. To learn more about Vue, refer to these articles.
2. Axios HTTP client
An HTTP client is useful whenever a request needs to be sent to another server. As we all know, the callback is an old concept. So we need an HTTP client which is promise-based.
A promise-based client returns promises rather than accepting callbacks. The Promise
object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. An Axios is a promise-based HTTP client for the browser and node.js.
Along with node.js, Axios supports almost all the latest versions of browsers i.e. Firefox, Chrome, IE, Edge, Safari for sending requests.
It allows making XMLHttpRequests from the browser. XMLHttpRequest
(XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.
See this Axios documentation for more in-depth details.
3. Vue 3 Axios
You can use the vue-axios
library to integrate our vue js app with Axios.
It binds the Axios to the vue
instance so you don’t have to import every time you use axios
.
import axios from 'axios' import VueAxios from 'vue-axios' const app = Vue.createApp(...) app.use(VueAxios, axios)
You can bind Axios to an app
instance or this
if you’re using a single file component.
3.1. Options Axios API
In option API, you can use axios
like this:
export default { name: 'App', methods: { getList() { this.axios.get(api).then((response) => { console.log(response.data) }) this.$http.get(api).then((response) => { console.log(response.data) }) } }
3.2. Vue composition API Axios
In composition API, we can’t use this
with setup
, use provide API to share the global instance properties first, then use inject
API to inject axios
to setup
:
const app = createApp(App).use(store) app.use(VueAxios, axios) app.provide('axios', app.config.globalProperties.axios) app.mount('#app')
import { createApp } from 'vue' import App from './App.vue' import store from './store' import axios from 'axios' import VueAxios from 'vue-axios' const app = createApp(App).use(store) app.use(VueAxios, axios) app.provide('axios', app.config.globalProperties.axios) app.mount('#app') import { inject } from 'vue' export default { name: 'Comp', setup() { const axios: any = inject('axios') const getList = (): void => { axios .get(api) .then((response: { data: any }) => { console.log(response.data) }); }; return { getList } } }
4. Conclusion
To sum up, we have learned to use Axios with Vue 3 project.