跳到内容

useNetwork

类别
导出大小
889 B
上次更改
3 周前

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

演示

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

用法

js
import { useNetwork } from '@vueuse/core'

const { isOnline, offlineAt, downlink, downlinkMax, effectiveType, saveData, type } = useNetwork()

console.log(isOnline.value)

要用作对象,请用 reactive() 包裹它

js
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>

类型声明

显示类型声明
typescript
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
 */
export declare function useNetwork(
  options?: ConfigurableWindow,
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>

源代码

源代码演示文档

贡献者

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

更新日志

v12.4.0 于 2025/1/10
dd316 - feat: 在所有可能的地方使用被动事件处理程序 (#4477)
v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: 删除 Vue 2 支持,优化 bundles 并清理代码 (#4349)
v11.1.0 于 2024/9/16
99179 - fix: 返回不可变的值 (#4187)

根据 MIT 许可证发布。