Skip to content

useBattery

类别
导出大小
823 B
最近修改
2 days ago

反应式 电池状态 API,更常被称为电池 API,提供有关系统电池电量的信息,并允许你通过事件通知接收电池电量或充电状态变化时的信息。可以利用此功能在电池电量低时调整应用的资源使用以减少电池消耗,或者在电池耗尽前保存更改以防止数据丢失。

🌐 Reactive Battery Status API, more often referred to as the Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss.

示例

isSupported: false
charging: false
chargingTime: 0
dischargingTime: 0
level: 1

用法

🌐 Usage

ts
import { 
useBattery
} from '@vueuse/core'
const {
isSupported
,
charging
,
chargingTime
,
dischargingTime
,
level
} =
useBattery
()
状态类型描述
isSupportedBoolean当前浏览器是否支持电池状态 API。
chargingBoolean设备当前是否正在充电。
chargingTimeNumber设备充满电所需的秒数。
dischargingTimeNumber设备放电至完全耗尽所需的秒数。
levelNumber表示当前电量水平的一个介于 0 到 1 之间的数字。

浏览器支持

电池状态 API 的浏览器支持有限。目前仅在基于 Chromium 的浏览器中可用。在使用这些值之前,请始终检查 isSupported

用例

🌐 Use-cases

我们的应用通常不关心电池电量,我们可以对我们的应用进行一些调整,这对低电量用户更加友好。

🌐 Our applications normally are not empathetic to battery level, we can make a few adjustments to our applications that will be more friendly to low battery users.

  • 触发特殊的“夜间模式”省电主题设置。
  • 停止自动播放新闻源中的视频。
  • 禁用一些不重要的后台工作线程。
  • 限制网络调用并减少 CPU/内存消耗。

组件用法

🌐 Component Usage

vue
<template>
  <UseBattery v-slot="{ 
isSupported
,
charging
,
level
}">
<
div
v-if="
isSupported
">
<
p
>Is Charging: {{
charging
}}</
p
>
<
p
>Battery Level: {{ (
level
* 100).
toFixed
(0) }}%</
p
>
</
div
>
<
div
v-else>
Battery API not supported </
div
>
</UseBattery> </template>