Skip to content

useNetwork

類別
導出大小
889 B
上次變更
3 週前

響應式 網路狀態。Network Information 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.dev.org.tw/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 支援,優化捆綁包並清理 (#4349)
v11.1.0 於 2024/9/16
99179 - fix: 返回不可變的值 (#4187)

根據 MIT 許可證發布。