跳到主要内容

useNetwork

分类
导出大小
964 B
上次更改
3 个月前

响应式的网络状态。Network Information API 提供有关系统连接的一般连接类型(例如,“wifi”、“蜂窝网络”等)的信息。这可用于根据用户的连接选择高清内容或低清内容。整个 API 包括 NetworkInformation 接口的添加和 Navigator 接口的一个属性:Navigator.connection。

演示

用法

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
)

组件用法

此函数还通过 @vueuse/components 包提供了一个无渲染组件版本。了解更多用法

vue
<template>
  <UseNetwork v-slot="{ 
isOnline
,
type
}">
Is Online: {{
isOnline
}}
Type: {{
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>
/** * If the user is currently connected. */
isOnline
:
Readonly
<
ShallowRef
<boolean>>
/** * The time since the user was last connected. */
offlineAt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * At this time, if the user is offline and reconnects */
onlineAt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * The download speed in Mbps. */
downlink
:
Readonly
<
ShallowRef
<number | undefined>>
/** * The max reachable download speed in Mbps. */
downlinkMax
:
Readonly
<
ShallowRef
<number | undefined>>
/** * The detected effective speed type. */
effectiveType
:
Readonly
<
ShallowRef
<
NetworkEffectiveType
| undefined>>
/** * The estimated effective round-trip time of the current connection. */
rtt
:
Readonly
<
ShallowRef
<number | undefined>>
/** * If the user activated data saver mode. */
saveData
:
Readonly
<
ShallowRef
<boolean | undefined>>
/** * The detected connection/network type. */
type
:
Readonly
<
ShallowRef
<
NetworkType
>>
} /** * Reactive Network status. * * @see https://vueuse.org.cn/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)!: 重构组件并使其保持一致 (#4912)
v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
v12.4.0
dd316 - feat: 尽可能在所有地方使用被动事件处理程序 (#4477)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v11.1.0
99179 - 修复:返回不可变值 (#4187)

根据 MIT 许可证发布。