Skip to content

useAxios

axios 的封装。

¥Wrapper for axios.

示例

Loading: true
Finished: false
Aborted: false
Available in the @vueuse/integrations add-on.

安装

¥Install

bash
npm i axios@^1

用法

¥Usage

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
const {
data
,
isFinished
} =
useAxios
('/api/posts')

或使用 axios 的实例

¥or use an instance of axios

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
import
axios
from 'axios'
const
instance
=
axios
.
create
({
baseURL
: '/api',
}) const {
data
,
isFinished
} =
useAxios
('/posts',
instance
)

使用带有配置选项的 axios 实例

¥use an instance of axios with config options

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
import
axios
from 'axios'
const
instance
=
axios
.
create
({
baseURL
: '/api',
}) const {
data
,
isFinished
} =
useAxios
('/posts', {
method
: 'POST' },
instance
)

当你没有通过 url。默认值为 {immediate: false}

¥When you don't pass the url. The default value is {immediate: false}

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
const {
execute
} =
useAxios
()
execute
(url)

这里的 execute 函数 url 是可选的,url2 将取代 url1

¥The execute function url here is optional, and url2 will replace the url1.

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
const {
execute
} =
useAxios
(url1, {}, {
immediate
: false })
execute
(url2)

execute 函数只能接受 config

¥The execute function can accept config only.

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
const {
execute
} =
useAxios
(url1, {
method
: 'GET' }, {
immediate
: false })
execute
({
params
: {
key
: 1 } })
execute
({
params
: {
key
: 2 } })

execute 函数根据网络请求的结果进行解析。

¥The execute function resolves with a result of network request.

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
const {
execute
} =
useAxios
()
const
result
= await
execute
(url)

使用带有 immediate 选项的 axios 实例

¥use an instance of axios with immediate options

ts
import { 
useAxios
} from '@vueuse/integrations/useAxios'
import
axios
from 'axios'
const
instance
=
axios
.
create
({
baseURL
: '/api',
}) const {
data
,
isFinished
} =
useAxios
('/posts', {
method
: 'POST' },
instance
, {
immediate
: false,
})