当前位置:首页 > 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 获取用户位置,并转换为城市名称:

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实现时间天气

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

相关文章

java中如何获取当前时间

java中如何获取当前时间

获取当前时间的几种方法 使用 java.time 包(Java 8及以上推荐) import java.time.LocalDateTime; LocalDateTime currentTime =…

java如何获得当前时间

java如何获得当前时间

获取当前时间的几种方法 使用 java.time 包(Java 8及以上推荐) import java.time.LocalDateTime; import java.time.format.Da…

vue实现彩色时间

vue实现彩色时间

实现彩色时间的Vue方案 使用动态样式绑定 在Vue中可以通过v-bind:style动态绑定样式,结合Date对象实现彩色时间显示。创建计算属性返回当前时间字符串,再根据时间数值动态生成颜色。…

vue实现当前时间

vue实现当前时间

实现当前时间的Vue方法 在Vue中获取并显示当前时间可以通过以下方式实现: 方法一:使用data属性 new Vue({ el: '#app', data: { curren…

vue怎么实现当前时间

vue怎么实现当前时间

获取当前时间的方法 在Vue中获取当前时间可以通过JavaScript的Date对象实现。以下是几种常见的方式: 基本方法 new Date() // 返回当前时间的Date对象 格式化输出…

react如何查看渲染时间

react如何查看渲染时间

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