Lzh on GitHub

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

用法

import { useNetwork } from '@vueuse/core'

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

console.log(isOnline.value)

若要作为对象使用,请使用 reactive() 进行包裹:

import { reactive } from 'vue'

const network = reactive(useNetwork())

console.log(network.isOnline)

组件用法

此函数也通过 @vueuse/components 包提供了 无渲染组件版本了解更多关于用法的信息

<template>
  <UseNetwork v-slot="{ isOnline, type }">
    Is Online: {{ isOnline }}
    Type: {{ type }}
  </UseNetwork>
</template>

类型声明

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/useNetwork
 * @param options
 */
export declare function useNetwork(
  options?: ConfigurableWindow,
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>