How to fetch data in Vue with Axios
Fetching data from APIs with proper error handling and loading states is essential for building reliable Vue.js applications that interact with backend services. As the creator of CoreUI with over 25 years of development experience building Vue applications since 2014, I’ve used Axios extensively in our Vue components for its robust request/response interceptors and automatic JSON handling. The most effective approach is using Axios with Vue 3’s Composition API and reactive state management for clean, predictable data fetching. This method provides excellent error handling, request cancellation, and seamless integration with Vue’s reactivity system.
Use Axios with Vue 3 Composition API to fetch data with reactive state management and error handling.
import { ref, onMounted } from 'vue'
import axios from 'axios'
export default {
setup() {
const users = ref([])
const loading = ref(false)
const error = ref(null)
const fetchUsers = async () => {
loading.value = true
error.value = null
try {
const response = await axios.get('/api/users')
users.value = response.data
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
}
onMounted(() => {
fetchUsers()
})
return { users, loading, error, fetchUsers }
}
}
This approach uses Vue 3’s Composition API with ref() to create reactive state for data, loading status, and errors. Axios handles the HTTP request with automatic JSON parsing and provides excellent error handling through try-catch blocks. The onMounted() lifecycle hook triggers the initial data fetch when the component loads. The reactive state automatically updates the template when data changes, creating a responsive user experience with proper loading and error states.
Best Practice Note:
This is the data fetching pattern we use throughout CoreUI Vue components for reliable API integration with proper state management. Consider creating a custom composable function for reusable data fetching logic and always handle both network errors and HTTP error responses appropriately.



