@toplinker/vue3-axios-request
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

Vue3AxiosRequest

A wrapper for Axios with Vue3 componsition API, It's easy to use and support polling, retry, cache, debounce, throttle...

Features

  • Axios with Vue3 componsition API
  • Auto error retry
  • Reactive result with Vue3 ref
  • Interval polling
  • Debounce and throttle
  • Support any promise
  • Result caching support
  • Easy to use, simailar with axios.get(...) axios.post(...)
  • Written in Typescript, full type checking & code completion

Install

npm install @toplinker/vue3-axios-request
# or
yarn add @toplinker/vue3-axios-request

Usage

1. Quick Start

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

/**
 * 1. import `useAxiosRequest`
 */
import { useAxiosRequest } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 2. create a http instance
     */
    const http = useAxiosRequest();

    /**
     * 3. use http.get(...) or http.post(..) similar as axios usage,
     *    only with an extra ExecuteOptions.
     */
    const res = http.get(
      "https://api.github.com/search/repositories", // URL
      { params: { q: "vue3-axios-request" } }, // AxiosRequestConfig
      { retryCount: 10, retryInterval: 100 } // ExecuteOptions
    );

    /**
     * 4. return a result, include data, error, loading, run(), ... Thoses values
     *    are Ref<>, so it can directly used in html template
     */
    return { res };
  },
});
</script>

2. Usage of useAxiosGet,useAxioPost ...

As a alternative, you can use useAxiosGet, useAxiosPost to realize the same function without create a useAxiosRequest instance.

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

/**
 * 1. improt `useAxiosGet`,`useAxiosPost` etc.
 */
import { useAxiosGet } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 2. direct call function `useAxiosGet`.
     */
    const res = useAxiosGet(
      "https://api.github.com/search/repositories", // URL
      { params: { q: "vue3-axios-request" } }, // AxiosRequestConfig
      { retryCount: 10, retryInterval: 100 } // ExecuteOptions
    );

    /**
     * 3. return a result, include data, error, loading, run(), ... Thoses values
     *    are Ref<>, so it can directly used in html template
     */
    return { res };
  },
});
</script>

3. With Preset Settings

When create useAxiosRequest instance. you can preset some default AxiosRequestConfig and ExecuteOptions.

The full AxiosRequestConfig API, please see Axios Official Doc.

The full ExecuteOptions API, see below [API/ExecuteOptions] section.

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import { useAxiosRequest } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. When create a AxiosRequest instance, preset some ExecuteOptions and AxiosRequestConfig
     */
    const http = useAxiosRequest(
      {
        debounceInterval: 300,
        loadingDelay: 200,
        retryCount: 10,
        retryInterval: 100,
        manual: true,
      },
      { baseURL: "https://api.github.com/" }
    );

    const res = http.get(
      "/search/repositories", // URL
      { params: { q: "vue3-axios-request" } } // AxiosRequestConfig
      // ExecuteOptions with preset setting
    );

    return { res };
  },
});
</script>

4. Multi Global Settings

useExecutionOptions

You can use useExecuteOptions('name') function to create a ExecuteOptions with a global name.

When execute useExecuteOptions('name'), if the name never used before, it will create a new one.

If the name alreay exists, it will return from global.

useAxios

Similar with useExecuteOptions('name'), useAxios('name') can create multiple global AxiosInstance

with different default request config, or different interceptors.

useExecuteOptions() and useAxios() without name, it will set the name as default

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAxiosRequest, useExecuteOptions, useAxios } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. Create a new global ExecuteOptions with name `MyOptions`,
     *    and set it's default value
     */
    let myoptions = useExecuteOptions("MyOptions");
    myoptions.debounceInterval = 300;
    myoptions.retryCount = 10;
    myoptions.retryInterval = 100;
    myoptions.manual = true;
    // myoptions....

    /**
     * 2. Create a new global AxiosInstance with name `MyAxios`,
     *    then you can set the default AxiosRequestConfig and
     *    request or response interceptors
     */
    let myaxios = useAxios("MyAxios");
    myaxios.defaults.baseURL = "https://api.github.com/";
    // myaxios.interceptors.request.use(...)
    // myaxios.interceptors.response.use(...)

    /**
     * 3. Create AxiosRequest with global Axios and ExecuteOption by name.
     *    The name is case-insensitive
     */
    const http = useAxiosRequest("myoptions", "myaxios");
    const res = http.get(
      "/search/repositories", // URL
      { params: { q: "vue3-axios-request" } } // AxiosRequestConfig
      // ExecuteOptions with global setting
    );

    return { res };
  },
});

5. Run with parameters

As a alternative with static AxiosRequestConfig, you can also use a function with some parameters and return a AxiosRequestConfig.

After with functional AxiosRequestConfig, use run(...) can change the parameter to get different result.

<template>
  <button @click.prevent="res.run('vue2-axios')">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAxiosRequest } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. Create a function return AxiosRequestConfig.
     *    it will use ExecutionOptions's `defaultParams` as arguments
     */
    const res = useAxiosRequest().get(
      "https://api.github.com/search/repositories",
      (search: string) => {
        return { params: { q: search } };
      }, // arrow function return a AxiosRequestConfig
      { defaultParams: ["vue3-axios-request"] } // ExecuteOptions with defaultParams
    );

    return { res };

    /**
     * 2. You can use `res.run(...)`, set new parameters to change the AxiosRequestConfig,
     *    then it will get different result data.
     *    (see in html template `@click.prevent="res.run('vue2-axios')`, [Line 2])
     */
  },
});
</script>

6. Run any Promise

We also provide useRequest to execute any Promise function. the useage is same as useAxiosRequest, just replace the AxiosRequestConfig with a Promise function.

Below example, we use fetch to replace axios. but any Promise function (even without network request) still works.

<template>
  <button @click.prevent="res.run('vue2-axios')">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useRequest } from "@toplinker/vue3-axios-request";

export default defineComponent({
  setup() {
    /**
     * 1. Create any funtion which return a Promise<R>
     */
    const query = (search: string) => {
      return fetch("https://api.github.com/search/repositories?q=" + search);
    };

    /**
     * 2. Execute `useRequest(...)` with default parameters
     */
    const res = useRequest(query, { defaultParams: ["vue3-axios-request"] });

    /**
     * 3. All `ExecuteOptions` and result features same as `useAxiosRequest`
     */
    return { res };

    /**
     * 4. Also can use `res.run(...)`, set new parameters to get different result data.
     *    (see in html template `@click.prevent="res.run('vue2-axios')`, [Line 2])
     */
  },
});
</script>

API

ExecuteOptions

Option DataType Description
initData any Initial result data
defaultParams any[] Default parameters
pollingInterval number Polling Interval (ms)
debounceInterval number Debounce Interval (ms)
throttleInterval number Throttle Interval (ms)
cacheKey string Cache key, use with cacheTime, next time if the cache is valid, will return cache value
cacheTime number Cache expire time (seconds)
retryCount number Max error retry count
retryInterval number Each error retry interval (ms)
loadingDelay number Delay to set loading (ms)
manual boolean If true will not auto execute, need manually call run() function
onBefore (params: P) => void Before execution callback
resultInterceptor (data: R ) => any If service is sucess, use this interceptor to throw logic error
errorInterceptor (error: Error) => Error Error interceptor
formatResult (data: R ) => any Data format callback(data is resultInterceptor returned value), the return value will set to res.data
onSuccess (data:R, params: P) => void Success callback
onError (error: Error, params: P) => void Error callback
onAfter (data: R , error: Error , params: P) After callback, nomatter success or error
defaultAxios string or AxiosRequestConfig Default global axios name or a specific AxiosRequestConfig
defaultOptions string or ExecuteOptions Default global ExecuteOptions name or a specific settings

RequestResult

Key DataType Description
loading Ref<boolean> Loading flag
data Ref<R> Result data
error Ref<Error> Error data
params Ref<any[]> Last run parameters
run (...args: P) => Promise<R> Run request with new parameters
cancel () => void Cancel request
refresh () => Promise<R> Run request wit last parameters
mutate (newdata: R) => void Change result data

All Functions

Function Description
useRequest(promise) Execute a Promise function
useAxiosRequest(options, axios) Create a request instance with preset options and axios
useAxiosRequest().get(url, params, options) A wapper for axios.get() with options
useAxiosRequest().post(url, params, options) A wapper for axios.post() with options
useAxiosRequest().delete(url, params, options) A wapper for axios.delete() with options
useAxiosRequest().put(url, params, options) A wapper for axios.put() with options
useAxiosRequest().patch(url, params, options) A wapper for axios.patch() with options
useAxiosRequest().head(url, params, options) A wapper for axios.head() with options
useAxiosRequest().request(params, options) A wapper for axios.request() with options
useAxiosGet(url, params, options) A quick usage of useAxiosRequest().get(url, params, options)
useAxiosPost(url, params, options) A quick usage of useAxiosRequest().post(url, params, options)
useAxiosDelete(url, params, options) A quick usage of useAxiosRequest().delete(url, params, options)
useAxiosPut(url, params, options) A quick usage of useAxiosRequest().put(url, params, options)
useAxiosPatch(url, params, options) A quick usage of useAxiosRequest().patch(url, params, options)
useAxiosHead(url, params, options) A quick usage of useAxiosRequest().head(url, params, options)
useAxios(name) Create or get a global AxiosInstance
useExecuteOptions(name) Create or get a global ExecuteOption
allAxiosInstance() Return all global AxiosInstance
allExecuteOptions() Return all global ExecuteOptions

Changelog

1.2.1

  • Compile esm with es6.

1.2.0

  • Change run() return type from Promise<void> to Promise<R>

1.1.3

  • Add ExecuteOptions.errorInterceptor

1.1.2

  • Add ExecuteOptions.resultInterceptor

1.1.1

  • Change post, put, patch signature from .post(url, data, options) to .post(url, param, options).

1.0.4

  • Fix README.

1.0.3

  • Fix TS compiler options, downgrade from ESNext to ES2015.

1.0.2

  • Fix dependencies in package.json

1.0.1

  • Change useOptions to useExecuteOptions, make it's meaning clearer.
  • Improve and fix README

1.0.0

  • First release

Package Sidebar

Install

npm i @toplinker/vue3-axios-request

Weekly Downloads

1

Version

1.2.1

License

MIT

Unpacked Size

215 kB

Total Files

13

Last publish

Collaborators

  • charlie.zhuo
  • kj.wu
  • tony-gm
  • chenqiuyan