当前地区位置的实时天气,具体代码如下
<div class="weather">
{{ weatherDescription }} {{ temperature }}°C
</div>
<script>
import axios from "axios";
export default {
data() {
return {
temperature: "",
weatherDescription: "",
};
},
methods: {
getWeather() {
// 调用和风天气API,传入城市代码和API密钥
axios
.get("https://devapi.qweather.com/v7/weather/now", {
params: {
location: "CN101190107",
key: "ad937e721eab42c0a39be80c121b25e2",
},
})
.then((response) => {
console.log(response);
// 处理API响应,获取温度和天气情况
const weatherData = response.data.now;
const temperature = weatherData.temp;
const weatherDescription = weatherData.text;
// 将数据存储到组件状态中
this.temperature = temperature;
this.weatherDescription = weatherDescription;
})
.catch((error) => {
console.log(error);
});
},
},
mounted() {
let now = new Date();
this.year = now.getFullYear();
this.month = now.getMonth() + 1;
this.day = now.getDate();
// 七天请求一次数据
// setInterval(() => {
// console.log(1111111111);
// axios
// .get("https://devapi.qweather.com/v7/weather/now", {
// params: {
// location: "CN101190107",
// key: "ad937e721eab42c0a39be80c121b25e2",
// },
// })
// .then((response) => {
// console.log(response);
// // 处理API响应,获取温度和天气情况
// const weatherData = response.data.now;
// const temperature = weatherData.temp;
// const weatherDescription = weatherData.text;
// // 将数据存储到组件状态中
// this.temperature = temperature;
// this.weatherDescription = weatherDescription;
// })
// .catch((error) => {
// console.log(error);
// });
// }, 7 * 24 * 60 * 60 * 1000);
},
created() {
this.getWeather();
// setInterval(() => {
// this.currentTime = new Date().toLocaleTimeString();
// }, 1000);
},
};
</script>