useBattery.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { computed, onMounted, reactive } from 'vue';
  2. export type Battery = {
  3. charging: boolean; // 当前电池是否正在充电
  4. chargingTime: number; // 距离充电完毕还需多少秒,如果为0则充电完毕
  5. dischargingTime: number; // 代表距离电池耗电至空且挂起需要多少秒
  6. /** 代表电量的放大等级,这个值在 0.0 至 1.0 之间 */
  7. level: number;
  8. [key: string]: any;
  9. };
  10. export const useBattery = () => {
  11. const battery = reactive<Battery>({
  12. charging: false,
  13. chargingTime: 0,
  14. dischargingTime: 0,
  15. level: 100,
  16. });
  17. // 当前浏览器是否支持Battery API
  18. const isSupported = navigator && 'getBattery' in navigator;
  19. // 更新电池使用状态
  20. const updateBattery = (target) => {
  21. for (const key in battery) {
  22. battery[key] = target[key];
  23. }
  24. battery.level = battery.level * 100;
  25. };
  26. // 计算电池剩余可用时间
  27. const calcDischargingTime = computed(() => {
  28. const hour = battery.dischargingTime / 3600;
  29. const minute = (battery.dischargingTime / 60) % 60;
  30. return `${~~hour}小时${~~minute}分钟`;
  31. });
  32. // 电池状态
  33. const batteryStatus = computed(() => {
  34. if (battery.charging && battery.level >= 100) {
  35. return '已充满';
  36. } else if (battery.charging) {
  37. return '充电中';
  38. } else {
  39. return '已断开电源';
  40. }
  41. });
  42. onMounted(async () => {
  43. const BatteryManager: Battery = (await (window.navigator as any).getBattery?.()) || {};
  44. updateBattery(BatteryManager);
  45. console.log(BatteryManager, '电池');
  46. // 电池充电状态更新时被调用
  47. BatteryManager.onchargingchange = ({ target }) => {
  48. updateBattery(target);
  49. console.log(target, '电池充电状态改变了');
  50. };
  51. // 电池充电时间更新时被调用
  52. BatteryManager.onchargingtimechange = ({ target }) => {
  53. updateBattery(target);
  54. console.log(target, '电池充电了');
  55. };
  56. // 电池断开充电时间更新时被调用
  57. BatteryManager.ondischargingtimechange = ({ target }) => {
  58. updateBattery(target);
  59. console.log(target, '电池断开充电了');
  60. };
  61. // 电池电量更新时被调用
  62. BatteryManager.onlevelchange = ({ target }) => {
  63. updateBattery(target);
  64. console.log(target, '电量更新了');
  65. };
  66. // new Intl.DateTimeFormat('zh', {
  67. // year: 'numeric',
  68. // month: '2-digit',
  69. // day: '2-digit',
  70. // hour: '2-digit',
  71. // minute: '2-digit',
  72. // second: '2-digit',
  73. // hour12: false
  74. // }).format(new Date())
  75. });
  76. return {
  77. battery,
  78. isSupported,
  79. batteryStatus,
  80. calcDischargingTime,
  81. } as const;
  82. };