Skip to content

useBattery

类别
导出体积
869 B
上次更改
2 months ago

响应式的 Battery Status API,更常被称为电池 API,提供有关系统电池充电级别的信息,并允许在电池级别或充电状态发生变化时发送事件通知。这可以用来调整你的应用程序的资源使用,以减少电池耗尽时的电池消耗,或在电池耗尽之前保存更改,以防止数据丢失。

示例

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

用法

ts
import { 
useBattery
} from '@vueuse/core'
const {
charging
,
chargingTime
,
dischargingTime
,
level
} =
useBattery
()
状态类型描述
chargingBoolean设备当前是否正在充电。
chargingTimeNumber直到设备完全充满的秒数。
dischargingTimeNumber直到设备完全放电的秒数。
levelNumber介于 0 和 1 之间的数字,表示当前的充电水平。

使用场景

我们的应用程序通常不会关注电池电量,但我们可以对应用程序进行一些调整,使其对电量较低的用户更友好。

  • 触发特殊的 “省电模式” 暗色主题设置。
  • 停止自动播放新闻动态中的视频。
  • 禁用一些不是必要的后台任务。
  • 限制网络调用并减少 CPU/内存消耗。

Component Usage

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

vue
<template>
  <UseBattery v-slot="{ 
charging
}">
正在充电: {{
charging
}}
</UseBattery> </template>

类型声明

ts
export interface BatteryManager extends EventTarget {
  
charging
: boolean
chargingTime
: number
dischargingTime
: number
level
: number
} /** * 响应式电池状态 * * @see https://vueuse.org/useBattery * * @__NO_SIDE_EFFECTS__ */ export declare function
useBattery
(
options
?:
ConfigurableNavigator
): {
isSupported
:
ComputedRef
<boolean>
charging
:
ShallowRef
<boolean, boolean>
chargingTime
:
ShallowRef
<number, number>
dischargingTime
:
ShallowRef
<number, number>
level
:
ShallowRef
<number, number>
} export type
UseBatteryReturn
=
ReturnType
<typeof
useBattery
>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
SerKo
IlyaL
Robin
Anthony Fu
Tachibana Shin
丶远方
vaakian X
Jelf
Piet Althoff
Shinigami
wheat
Alex Kozack
Antério Vieira

更新日志

8c521 - feat(components)!: refactor components and make them consistent (#4912)
d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
30245 - fix: fake signal API support in some utilities (#3634)