vue实现时间天气
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>
注意事项
- 需要替换
YOUR_API_KEY为实际的 OpenWeatherMap API 密钥 - 地理位置服务需要用户授权
- 考虑添加错误处理,如 API 请求失败的情况
- 对于生产环境,建议使用 axios 等 HTTP 客户端替代原生 fetch
- 可以添加加载状态,提升用户体验
样式美化建议
<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>






