import { defineStore } from 'pinia'; import storage from "@/utils/storage.js" export const useWeatherStore = defineStore('weather', { state: () => { return { location: storage.getCache('location') || {}, weather: { current: {}, after: [], daily: {}, }, city:"" }; }, actions: { setlocation(location) { storage.setCache('location', location) this.location = location }, setWeather(data) { const combinedData = data.hourly.time.map((time, index) => ({ time, temperature: fixed(data.hourly.temperature_2m[index]), weathercode: data.hourly.weather_code[index] })) // 当前天气 this.weather.current = { time: data.current.time, temperature: fixed(data.current.temperature_2m), weathercode: data.current.weather_code } // 接下来的天气 const givenTime = data.current.time const filteredArray = combinedData.filter(obj => obj.time > givenTime).slice(0, 4); const formattedArray = filteredArray.map(obj => ({ ...obj, time: formatTime(obj.time) })); this.weather.after = formattedArray // 整日天气 const tempDaily = combinedData.slice(0, 24).sort((a, b) => a.temperature - b.temperature) this.weather.daily = { des: data.daily.weather_code[0], lowTemp: tempDaily[0].temperature, highTemp: tempDaily[23].temperature } }, }, // 开始数据持久化 persist: true, }) export function getLocalState() { const localSetting = storage.getCache('location') return localSetting } export function fixed(num) { return num.toFixed() } export function formatTime(time) { const date = new Date(time); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${hours}:${minutes}`; };