コンテンツにスキップ

useNetwork

カテゴリ
エクスポートサイズ
814 B
最終更新
先週

リアクティブなネットワーク状態。 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: Readonly<Ref<boolean>>
  /**
   * If the user is currently connected.
   */
  isOnline: Readonly<Ref<boolean>>
  /**
   * The time since the user was last connected.
   */
  offlineAt: Readonly<Ref<number | undefined>>
  /**
   * At this time, if the user is offline and reconnects
   */
  onlineAt: Readonly<Ref<number | undefined>>
  /**
   * The download speed in Mbps.
   */
  downlink: Readonly<Ref<number | undefined>>
  /**
   * The max reachable download speed in Mbps.
   */
  downlinkMax: Readonly<Ref<number | undefined>>
  /**
   * The detected effective speed type.
   */
  effectiveType: Readonly<Ref<NetworkEffectiveType | undefined>>
  /**
   * The estimated effective round-trip time of the current connection.
   */
  rtt: Readonly<Ref<number | undefined>>
  /**
   * If the user activated data saver mode.
   */
  saveData: Readonly<Ref<boolean | undefined>>
  /**
   * The detected connection/network type.
   */
  type: Readonly<Ref<NetworkType>>
}
/**
 * Reactive Network status.
 *
 * @see https://vueuse.dokyumento.jp/useNetwork
 * @param options
 */
export declare function useNetwork(
  options?: ConfigurableWindow,
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>

ソース

ソースデモドキュメント

貢献者

Anthony Fu
Jelf
Anthony Fu
Daniil Rudnov
丶远方
vaakian X
Kirk Lin
Lexpeartha
webfansplz
wheat
Alex Kozack
Antério Vieira

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを終了、バンドルを最適化、クリーンアップ (#4349)
v11.1.0 2024/09/16
99179 - 修正: 不変な値を返す (#4187)
v9.11.0 2023/01/17
d5321 - 修正(コンポーネント): defineComponentをpureとしてマーク (#2623)

MITライセンスの下でリリースされています。