Skip to content

Vue and AJAX

Modern web applications are rarely purely static; they usually need to dynamically exchange data with servers. For example, fetching article lists, submitting user information, searching data, etc. This process is usually achieved through AJAX (Asynchronous JavaScript and XML) technology.

AJAX allows webpages to exchange data with servers without reloading the entire page and update parts of the webpage content.

How to Use AJAX in Vue?

First, to clarify: Vue itself does not contain any AJAX functionality. Vue's core library focuses on the view layer and doesn't care how you fetch data. You can use any method you like to initiate HTTP requests.

Common AJAX technologies and libraries include:

  1. Browser's native fetch API: This is a standard API built into modern browsers for making network requests. It's based on Promise and has concise syntax.
  2. Third-party libraries like axios: This is a very popular and powerful HTTP client library. It provides more features such as request and response interceptors, canceling requests, automatic JSON data conversion, etc., and can be used in both browser and Node.js environments.

Using the fetch API

fetch is the most direct method because it doesn't require installing any additional dependencies.

Below is an example of using fetch in the onMounted lifecycle hook of a Vue component to fetch data:

vue
<script setup>
import { ref, onMounted } from 'vue'

const posts = ref([])
const loading = ref(true)
const error = ref(null)

async function fetchData() {
  loading.value = true
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts')
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    posts.value = await response.json()
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div>
    <h1>Posts</h1>
    <div v-if="loading">Loading...</div>
    <div v-if="error" style="color: red;">{{ error }}</div>
    <ul v-if="posts.length">
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

In this example:

  1. We defined three reactive states posts, loading, and error to manage data, loading state, and error information.
  2. The fetchData function uses async/await syntax to handle the asynchronous fetch request.
  3. We use a try...catch...finally block to handle possible network errors and update the loading state.
  4. Call fetchData in the onMounted hook so the component starts fetching data as soon as it's mounted.

Although fetch is convenient, using a library like axios for complex applications has several benefits:

  • More Features: Provides advanced features like interceptors, request cancellation, timeout settings, etc.
  • Better Error Handling: axios treats non-2xx HTTP status codes as errors and rejects the Promise, while fetch only rejects on network failure—for 404 or 500 errors, it still resolves.
  • Automatic Data Conversion: axios automatically converts request and response data to JSON, while fetch requires manually calling .json().
  • Browser Compatibility: axios has better compatibility with older browsers.

In the next chapter, we will detail how to integrate and use axios in Vue.

Content is for learning and research only.