Vue — API Calls
Using fetch
<script>
export default {
data() {
return {
users: [],
loading: false,
error: null
}
},
methods: {
async fetchUsers() {
this.loading = true
try {
const res = await fetch('https://api.example.com/users')
this.users = await res.json()
} catch (err) {
this.error = err.message
} finally {
this.loading = false
}
}
},
mounted() {
this.fetchUsers()
}
}
</script>
Using axios
npm install axios
// api.js
import axios from 'axios'
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
})
export default api
GET request
<script>
import api from '@/api'
export default {
data() {
return { users: [] }
},
async created() {
const { data } = await api.get('/users')
this.users = data
}
}
</script>
POST request
<script>
import api from '@/api'
export default {
methods: {
async createUser(userData) {
const { data } = await api.post('/users', userData)
console.log('Created:', data)
}
}
}
</script>
PUT/PATCH/DELETE
// PUT
await api.put(`/users/${id}`, userData)
// PATCH
await api.patch(`/users/${id}`, { name: 'New Name' })
// DELETE
await api.delete(`/users/${id}`)
Error handling
try {
const { data } = await api.get('/users')
} catch (error) {
if (error.response) {
// Server responded with error
console.error(error.response.data)
} else if (error.request) {
// No response received
console.error('Network error')
}
}
Mini Practice
- Fetch data with fetch API
- Set up axios with interceptors
- Handle loading and error states
- Create CRUD operations
Up Next
Continue with Animations - Transitions and effects.
Related Topics
Frequently Asked Questions about API Calls
What is API Calls in Vue?
API Calls is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn API Calls?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn API Calls.
Why is API Calls important in Vue?
API Calls is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.