useNetwork
響應式 網路狀態。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>