Using Axios in Vue3 can be configured and used through the following steps:
- Install Axios:
npm install axios
- Create a file in your project
api.js
and import Axios and Vue:
import axios from 'axios'
import { reactive } from 'vue'
- Create a reactive object and instantiate Axios:
const state = reactive({
data: null,
loading: false,
error: null
})
const http = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
- Create methods in
api.js
the file to send HTTP requests:
const fetchData = async () => {
state.loading = true
try {
const response = await http.get('/data')
state.data = response.data
} catch (error) {
state.error = error
} finally {
state.loading = false
}
}
api.js
Import and call the method in the component :
import { fetchData } from '@/api'
export default {
name: 'MyComponent',
async created() {
await fetchData()
}
}
- Use reactive data in templates:
<template>
<div v-if="state.loading">Loading...</div>
<div v-else-if="state.error">{
{ state.error.message }}</div>
<div v-else>{
{ state.data }}</div>
</template>
<script>
import { state } from '@/api'
export default {
name: 'MyComponent',
setup() {
return { state }
}
}
</script>
The above is how to configure and use Axios in Vue3.