Getting Started
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
# or
yarn add vue-request
# or
pnpm install vue-request
CDN
For production environments, we recommend linking to a specific version and build file to avoid unexpected breaking changes caused by new versions.
<script src="https://unpkg.com/vue-request/dist/vue-request.min.js"></script>
Once you add it to your page, you can access our exported methods in window.VueRequest
.
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
takes a Service
function. Service
is an asynchronous request function, which means you can use axios to fetch data and return a Promise. More detailed information can be found in Data Fetching.
useRequest
also returns three values, data
, loading
, and error
. When the request is not completed yet, data
will be undefined
, and loading
will be set to true
. When the request is finished, data
and error
will be set according to the request result, and the page will be rendered. This is because data
, loading
, and error
are Vue's reactive references (shallowRef)open in new window, and their values will be modified according to the request status and result.