Skip to content

useBattery

反应式 电池状态 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

js
import { useBattery } from '@vueuse/core'

const { charging, chargingTime, dischargingTime, level } = useBattery()
状态类型描述
chargingBoolean如果设备当前正在充电。
chargingTimeNumber设备充满电之前的秒数。
dischargingTimeNumber设备完全放电之前的秒数。
levelNumber0 到 1 之间的数字,表示当前电量。

用例

¥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.

  • 触发特殊的 "dark-mode" 省电主题设置。

    ¥Trigger a special "dark-mode" battery saver theme settings.

  • 停止自动播放新闻源中的视频。

    ¥Stop auto playing videos in news feeds.

  • 禁用一些不重要的后台工作线程。

    ¥Disable some background workers that are not critical.

  • 限制网络调用并减少 CPU/内存消耗。

    ¥Limit network calls and reduce CPU/Memory consumption.

组件用法

¥Component Usage

vue
<template>
  <UseBattery v-slot="{ charging }">
    Is Charging: {{ charging }}
  </UseBattery>
</template>

类型声明

typescript
export interface BatteryManager extends EventTarget {
  charging: boolean
  chargingTime: number
  dischargingTime: number
  level: number
}
/**
 * Reactive Battery Status API.
 *
 * @see https://vueuse.org/useBattery
 */
export declare function useBattery(options?: ConfigurableNavigator): {
  isSupported: ComputedRef<boolean>
  charging: Ref<boolean>
  chargingTime: Ref<number>
  dischargingTime: Ref<number>
  level: Ref<number>
}
export type UseBatteryReturn = ReturnType<typeof useBattery>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号