Skip to content

useNetwork

响应式地获取网络状态。网络信息 API 提供了有关系统连接的信息,例如一般连接类型 (例如,“wifi”,“cellular” 等)。这可以用于根据用户的连接选择高清晰度内容或低清晰度内容。整个 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 { useNetwork } from '@vueuse/core'
// ---cut---
import { reactive } from 'vue'

const network = reactive(useNetwork())

console.log(network.isOnline)

组件使用

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

Type Declarations

ts
export interface UseNetworkOptions extends ConfigurableWindow {}
export type NetworkType =
  | "bluetooth"
  | "cellular"
  | "ethernet"
  | "none"
  | "wifi"
  | "wimax"
  | "other"
  | "unknown"
export type NetworkEffectiveType = "slow-2g" | "2g" | "3g" | "4g" | undefined
export interface NetworkState extends Supportable {
  /**
   * 用户当前是否连接到网络。
   */
  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>>
}
export type UseNetworkReturn = Readonly<NetworkState>
/**
 * 响应式网络状态。
 *
 * @see /useNetwork
 * @param options
 *
 * @__NO_SIDE_EFFECTS__
 */
export declare function useNetwork(
  options?: UseNetworkOptions,
): UseNetworkReturn