useNetwork
响应式的网络状态。Network Information API 提供有关系统连接的一般连接类型(例如,“wifi”、“蜂窝网络”等)的信息。这可用于根据用户的连接选择高清内容或低清内容。整个 API 包括 NetworkInformation 接口的添加和 Navigator 接口的一个属性:Navigator.connection。
演示
用法
ts
import { useNetwork } from '@vueuse/core'
const { isOnline, offlineAt, downlink, downlinkMax, effectiveType, saveData, type } = useNetwork()
console.log(isOnline.value)若要用作对象,请使用 reactive() 将其包装起来
ts
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>类型声明
显示类型声明
ts
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.cn/useNetwork
* @param options
*
* @__NO_SIDE_EFFECTS__
*/
export declare function useNetwork(
options?: ConfigurableWindow,
): Readonly<NetworkState>
export type UseNetworkReturn = ReturnType<typeof useNetwork>