Getting Started

Note

Make sure the Vue version is 3.x

Installation

You can install VueRequest with NPMopen in new window, YARNopen in new window, or a <script> via unpkg.comopen in new window

NPM

npm install vue-request@v1
# or
yarn add vue-request@v1

CDN

For production, we recommend linking to a specific version number and build to avoid unexpected breakage from newer versions.

<script src="https://unpkg.com/vue-request@v1/dist/vue-request.min.js"></script>

Once you've added this you will have access to the window.VueRequest object and its exports.

Usage

<template>
  <div>
    <div v-if="loading">loading...</div>
    <div v-if="error">failed to fetch</div>
    <div v-if="data">Hey! {{ data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  setup() {
    const { data, loading, error } = useRequest(service);

    return {
      data,
      loading,
      error,
    };
  },
});
</script>

In this example, useRequest accepts a service function. service is a asynchronous function. In other words, you can use axios to fetch data and return a Promise. More specific instructions can be viewed in Data Fetching.

useRequest also return 3 values: data, loading and error. When the request is not yet finished, data will be undefined and loading will be true. And when we get a response, it sets data and error based on the result of service and rerenders the component. This is because data and error are Reactivity(Refs)open in new window, and their values will be set by the service response.

Last Updated: 6/6/2023, 4:05:10 AM
Contributors: John