useNetwork
响应式地获取 网络状态。网络信息 API 提供了有关系统连接的信息,例如一般连接类型(例如,“wifi”,“cellular”等)。这可以用于根据用户的连接选择高清晰度内容或低清晰度内容。整个 API 由 NetworkInformation 接口的添加和 Navigator 接口的单个属性组成:Navigator.connection。
Demo
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)
组件使用
vue
<template>
<UseNetwork v-slot="{ isOnline, type }">
是否在线:{{ isOnline }} 类型:{{ type }}
</UseNetwork>
</template>
Type Declarations
Show Type Declarations
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.org/useNetwork
* @param options
*/
export declare function useNetwork(
options?: ConfigurableWindow,
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>