weather.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import {
  2. defineStore
  3. } from 'pinia';
  4. import storage from "@/utils/storage.js"
  5. export const useWeatherStore = defineStore('weather', {
  6. state: () => {
  7. return {
  8. location: storage.getCache('location') || {},
  9. weather: {
  10. current: {},
  11. after: [],
  12. daily: {},
  13. },
  14. city:""
  15. };
  16. },
  17. actions: {
  18. setlocation(location) {
  19. storage.setCache('location', location)
  20. this.location = location
  21. },
  22. setWeather(data) {
  23. const combinedData = data.hourly.time.map((time, index) => ({
  24. time,
  25. temperature: fixed(data.hourly.temperature_2m[index]),
  26. weathercode: data.hourly.weather_code[index]
  27. }))
  28. // 当前天气
  29. this.weather.current = {
  30. time: data.current.time,
  31. temperature: fixed(data.current.temperature_2m),
  32. weathercode: data.current.weather_code
  33. }
  34. // 接下来的天气
  35. const givenTime = data.current.time
  36. const filteredArray = combinedData.filter(obj => obj.time > givenTime).slice(0, 4);
  37. const formattedArray = filteredArray.map(obj => ({
  38. ...obj,
  39. time: formatTime(obj.time)
  40. }));
  41. this.weather.after = formattedArray
  42. // 整日天气
  43. const tempDaily = combinedData.slice(0, 24).sort((a, b) => a.temperature - b.temperature)
  44. this.weather.daily = {
  45. des: data.daily.weather_code[0],
  46. lowTemp: tempDaily[0].temperature,
  47. highTemp: tempDaily[23].temperature
  48. }
  49. },
  50. },
  51. // 开始数据持久化
  52. persist: true,
  53. })
  54. export function getLocalState() {
  55. const localSetting = storage.getCache('location')
  56. return localSetting
  57. }
  58. export function fixed(num) {
  59. return num.toFixed()
  60. }
  61. export function formatTime(time) {
  62. const date = new Date(time);
  63. const hours = String(date.getHours()).padStart(2, '0');
  64. const minutes = String(date.getMinutes()).padStart(2, '0');
  65. return `${hours}:${minutes}`;
  66. };