Skip to content

useNetwork

类别
导出体积
964 B
上次更改
2 months ago

响应式地获取网络状态。网络信息 API 提供了有关系统连接的信息,例如一般连接类型 (例如,“wifi”,“cellular” 等)。这可以用于根据用户的连接选择高清晰度内容或低清晰度内容。整个 API 由 NetworkInformation 接口的添加和 Navigator 接口的单个属性组成:Navigator.connection。

示例

isSupported: false
isOnline: true
saveData: false
type: unknown

使用方法

ts
import { 
useNetwork
} from '@vueuse/core'
const {
isOnline
,
offlineAt
,
downlink
,
downlinkMax
,
effectiveType
,
saveData
,
type
} =
useNetwork
()
console
.
log
(
isOnline
.
value
)

要将其作为对象使用,请使用 reactive() 进行包装

ts
import { 
reactive
} from 'vue'
const
network
=
reactive
(
useNetwork
())
console
.
log
(
network
.
isOnline
)

组件使用

vue
<template>
  <UseNetwork v-slot="{ 
isOnline
,
type
}">
是否在线:{{
isOnline
}} 类型:{{
type
}}
</UseNetwork> </template>

类型声明

显示类型声明
ts
export type 
NetworkType
=
| "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown" export type
NetworkEffectiveType
= "slow-2g" | "2g" | "3g" | "4g" | undefined
export interface NetworkState {
isSupported
:
ComputedRef
<boolean>
/** * 用户当前是否连接到网络。 */
isOnline
:
Readonly
<
ShallowRef
<boolean>>
/** * 用户上次连接到网络的时间。 */
offlineAt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * 在此时间点,如果用户处于离线状态并重新连接。 */
onlineAt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * 下载速度,以 Mbps 为单位。 */
downlink
:
Readonly
<
ShallowRef
<number | undefined>>
/** * 可达到的最大下载速度,以 Mbps 为单位。 */
downlinkMax
:
Readonly
<
ShallowRef
<number | undefined>>
/** * 检测到的有效速度类型。 */
effectiveType
:
Readonly
<
ShallowRef
<
NetworkEffectiveType
| undefined>>
/** * 当前连接的预估往返时间。 */
rtt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * 用户是否启用了数据节省模式。 */
saveData
:
Readonly
<
ShallowRef
<boolean | undefined>>
/** * 检测到的 connection/network 类型。 */
type
:
Readonly
<
ShallowRef
<
NetworkType
>>
} /** * 响应式网络状态。 * * @see https://vueuse.org/useNetwork * @param options * * @__NO_SIDE_EFFECTS__ */ export declare function
useNetwork
(
options
?:
ConfigurableWindow
,
):
Readonly
<NetworkState>
export type
UseNetworkReturn
=
ReturnType
<typeof
useNetwork
>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
SerKo
Jelf
IlyaL
Robin
IlyaL
Fernando Fernández
Alex Liu
Anthony Fu
Daniil Rudnov
丶远方
vaakian X
Kirk Lin
Lexpeartha
webfansplz
wheat
Alex Kozack
Antério Vieira

更新日志

8c521 - feat(components)!: refactor components and make them consistent (#4912)
d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
dd316 - feat: use passive event handlers everywhere is possible (#4477)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
99179 - fix: return immutable values (#4187)