SoFunction
Updated on 2025-04-03

Detailed explanation of the process of using fetch to implement data request in Vue3

Preface

In modern front-end development, data request is an indispensable link. And in Vue3, we have many ways to make data requests, which usesfetchMethods are a very common choice. This article will explain in detail how to use it in Vue3fetchTo implement data requests, and use sample code to guide you through the implementation process step by step.

1. What is fetch?

fetchIs a native JavaScript method used to send network requests to the server and process response results. Compared with traditional XHR requests,fetchMore modern and simple. Not only supports Promise, it also has a clearer API structure.

2. Introduction to Vue3

Vue3 is the latest version, which introduces many new features and optimizations, including Composition API (Composition API), faster renderers, and smaller packaging volumes. Using Vue3's combined API, you can organize and reuse code more flexibly, thereby improving development efficiency.

3. Basic steps to use fetch to make data requests

In usefetchWhen you are in the process of , the following steps are usually required:

  • Send a request: UsefetchMethod sends a request to the server.
  • Processing response: After receiving the response, parse the response data.
  • Handling Errors: Catch and process errors in requests or responses.

4. Use fetch in Vue3

Let's demonstrate how to use it in detail by building a simple Vue3 componentfetchMake a data request. Suppose we need to get user data from a REST API and display it on the page.

4.1 Create a Vue3 project

First, make sure you have Vue CLI installed. If not installed, you can use the following command to install:

npm install -g @vue/cli

Next, use the Vue CLI to create a new Vue3 project:

vue create vue-fetch-demo
cd vue-fetch-demo

4.2 Creating Components

existsrcCreate a directory callednew file, write the following code:

<template>
  <div>
    <h1>User List</h1>
    <div v-if="loading">Loading...</div>
    <div v-else-if="error">{{ error }}</div>
    <ul v-else>
      <li v-for="user in users" :key="">
        {{  }} ({{  }})
      </li>
    </ul>
  </div>
</template>

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

export default {
  name: 'UserList',
  setup() {
    const users = ref([]);
    const loading = ref(true);
    const error = ref(null);

    const fetchUsers = async () => {
      try {
        const response = await fetch('/users');
        if (!) {
          throw new Error('Network response was not ok ' + );
        }
        const data = await ();
         = data;
      } catch (err) {
         = ;
      } finally {
         = false;
      }
    };

    onMounted(() => {
      fetchUsers();
    });

    return {
      users,
      loading,
      error,
    };
  },
};
</script>

<style scoped>
  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    margin: 0.5rem 0;
  }
</style>

4.3 Detailed explanation of component code

  • Template section: We usedv-ifv-else-if,andv-elseInstructions are used to process loading states, error states and successful data acquisition states respectively.
  • Script section
    • ImportedrefandonMountedThese two Vue3 combination API functions.
    • usersloadinganderrorThese three responsive variables are used to save user data, load status and error information respectively.
    • fetchUsersA function is an asynchronous function that usesfetchMethod sends a request to the API, process the response and saves the data tousers, handling errors and updates at the same timeloadingstate.
    • When component mounts (onMountedhook), callfetchUsersFunction to get user data.
  • Style section: Some basic styles for beautifying the list.

4.4 Using components in the main application

Next, modifysrc/To use our newly createdUserListComponents. The code is as follows:

<template>
  <div >
    <UserList />
  </div>
</template>

<script>
import UserList from './components/';

export default {
  name: 'App',
  components: {
    UserList,
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

4.5 Run the application

Run the following command to start the project:

npm run serve

Open the browser and visit http://localhost:8080, and you should see a list of users whose data is fetched from the API via fetch.

5. Handle more complex data requests

In addition to basic GET requests, fetch can also be used to send POST, PUT, DELETE and other requests. We can set the request method and request header information by passing the second parameter. For example, send a POST request to the server:

const postData = async () => {
  const response = await fetch('/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: ({
      title: 'foo',
      body: 'bar',
      userId: 1,
    }),
  });
  const data = await ();
  (data);
};

6. Handle errors and cancel requests

When usingfetchWhen handling errors and timeouts are very important. If the server responds too long, you can use AbortController to cancel the request:

const controller = new AbortController();
const signal = ;

fetch('/users', { signal })
  .then(response =&gt; ())
  .then(data =&gt; (data))
  .catch(error =&gt; {
    if ( === 'AbortError') {
      ('Fetch aborted');
    } else {
      ('Fetch error: ', error);
    }
  });

// Call when cancellation is required();

Summarize

Through this article's explanation, I believe you have learned how to use it in Vue3fetchMake a data request. In actual projects, use them reasonablyfetchIt can greatly simplify the process of data request and processing and improve development efficiency. At the same time, combining it with Vue3's combined API can make the code more modular and easy to maintain.

The above is the detailed explanation of the process of using fetch to implement data requests in Vue3. For more information about Vue3 fetch data requests, please pay attention to my other related articles!