当前位置:首页 > VUE

vue实现时间天气

2026-02-22 11:03:10VUE

Vue 实现时间天气功能

获取当前时间

使用 JavaScript 的 Date 对象获取当前时间,并通过计算属性动态更新:

data() {
  return {
    currentTime: ''
  }
},
computed: {
  formattedTime() {
    const now = new Date()
    return now.toLocaleTimeString()
  }
},
mounted() {
  setInterval(() => {
    this.currentTime = new Date().toLocaleTimeString()
  }, 1000)
}

模板中显示时间:

<div>{{ formattedTime }}</div>

获取天气数据

通过天气 API(如 OpenWeatherMap)获取数据,需先注册 API 密钥:

data() {
  return {
    weatherData: null,
    apiKey: 'YOUR_API_KEY',
    city: 'Beijing'
  }
},
methods: {
  fetchWeather() {
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${this.apiKey}&units=metric`)
      .then(response => response.json())
      .then(data => {
        this.weatherData = data
      })
  }
},
mounted() {
  this.fetchWeather()
}

模板中显示天气信息:

<div v-if="weatherData">
  <p>温度: {{ weatherData.main.temp }}°C</p>
  <p>天气: {{ weatherData.weather[0].description }}</p>
</div>

自动定位城市

使用浏览器 Geolocation API 获取用户位置,并转换为城市名称:

vue实现时间天气

methods: {
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          this.fetchCityName(position.coords.latitude, position.coords.longitude)
        },
        error => {
          console.error('Error getting location:', error)
        }
      )
    }
  },
  fetchCityName(lat, lon) {
    fetch(`https://api.openweathermap.org/geo/1.0/reverse?lat=${lat}&lon=${lon}&limit=1&appid=${this.apiKey}`)
      .then(response => response.json())
      .then(data => {
        if (data.length > 0) {
          this.city = data[0].name
          this.fetchWeather()
        }
      })
  }
},
mounted() {
  this.getLocation()
}

完整组件示例

<template>
  <div>
    <h3>当前时间: {{ currentTime }}</h3>
    <div v-if="weatherData">
      <h3>{{ city }} 天气</h3>
      <p>温度: {{ weatherData.main.temp }}°C</p>
      <p>天气状况: {{ weatherData.weather[0].main }}</p>
      <p>湿度: {{ weatherData.main.humidity }}%</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentTime: '',
      weatherData: null,
      apiKey: 'YOUR_API_KEY',
      city: ''
    }
  },
  methods: {
    updateTime() {
      this.currentTime = new Date().toLocaleTimeString()
    },
    fetchWeather() {
      if (!this.city) return
      fetch(`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${this.apiKey}&units=metric`)
        .then(response => response.json())
        .then(data => {
          this.weatherData = data
        })
    },
    getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => {
            this.fetchCityName(position.coords.latitude, position.coords.longitude)
          },
          error => {
            console.error('Error getting location:', error)
            this.city = 'Beijing' // 默认城市
            this.fetchWeather()
          }
        )
      } else {
        this.city = 'Beijing'
        this.fetchWeather()
      }
    },
    fetchCityName(lat, lon) {
      fetch(`https://api.openweathermap.org/geo/1.0/reverse?lat=${lat}&lon=${lon}&limit=1&appid=${this.apiKey}`)
        .then(response => response.json())
        .then(data => {
          if (data.length > 0) {
            this.city = data[0].name
            this.fetchWeather()
          }
        })
    }
  },
  mounted() {
    setInterval(this.updateTime, 1000)
    this.getLocation()
  }
}
</script>

注意事项

  1. 需要替换 YOUR_API_KEY 为实际的 OpenWeatherMap API 密钥
  2. 地理位置服务需要用户授权
  3. 考虑添加错误处理,如 API 请求失败的情况
  4. 对于生产环境,建议使用 axios 等 HTTP 客户端替代原生 fetch
  5. 可以添加加载状态,提升用户体验

样式美化建议

<style scoped>
.weather-container {
  font-family: Arial, sans-serif;
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  background: linear-gradient(135deg, #72edf2 0%, #5151e5 100%);
  color: white;
}
.time-display {
  font-size: 1.5em;
  margin-bottom: 20px;
}
.weather-info {
  font-size: 1.2em;
}
</style>

标签: 天气时间
分享给朋友:

相关文章

vue实现时间显示

vue实现时间显示

实现时间显示的基本方法 在Vue中显示时间可以通过多种方式实现,包括使用原生JavaScript的Date对象、第三方库如moment.js或day.js。以下是几种常见的方法。 使用原生JavaS…

vue实现时间滑块

vue实现时间滑块

Vue 实现时间滑块 使用原生 HTML5 input range 通过 HTML5 的 input[type="range"] 结合 Vue 的数据绑定实现基础时间滑块: <temp…

vue如何实现动态时间

vue如何实现动态时间

Vue 实现动态时间的几种方法 使用 setInterval 更新数据 在 Vue 组件的 data 中定义一个时间变量,通过 setInterval 定时更新该变量。 data() { ret…

vue实现时间天气

vue实现时间天气

以下是在Vue中实现时间和天气功能的几种方法: 获取并显示当前时间 使用JavaScript的Date对象获取当前时间,并通过Vue的数据绑定显示: <template> <…

react如何查看渲染时间

react如何查看渲染时间

测量 React 组件渲染时间的方法 使用 React DevTools 的 Profiler 功能 React DevTools 提供了 Profiler 工具,可以记录组件的渲染时间。安装 Rea…

react如何根据时间来分类

react如何根据时间来分类

根据时间分类的实现方法 在React中根据时间分类数据通常涉及日期处理、数据分组和动态渲染。以下是几种常见场景的实现方式: 使用数组reduce方法分组 假设有一组带时间戳的数据,需要按天/月/年分…