19.天气查询(下)

用户可以输入城市名称,然后点击按钮来获取天气讯息。当用户输入城市名称并点击按钮时,应用会向天气API发送请求,然后显示返回的天气数据

首先先到openweathermap.org的网站看一下我们要用的api
http://img2.58codes.com/2024/20163468h8TTodYOfN.png

    <script>        new Vue({            el: '#app',            data() {                return {                    api_key: '申请的API_KEY',                    base_url: 'https://api.openweathermap.org/data/2.5/',                    city: '',                    weatherData: {},                    date: ''                }            },            methods: {                getWeather() {                    var that = this;                    axios.get(`${this.base_url}weather?q=${this.city}&units=metric&APPID=${this.api_key}`).then(response => {                        console.log(response.data)                        that.weatherData = response.data; // 更新weatherData                        this.updateDate(); // 调用更新日期函数                    }).catch(err => {                        console.error(err);                    });                },                updateDate() {                const currentDate = new Date();                const options = { year: 'numeric', month: 'long', day: 'numeric' };                this.date = currentDate.toLocaleDateString('en-US', options);                }            }        });    </script>

输入内容(城市名称)后按下enter,然后会看到像是这样的回传结果,我们需要的是main及weather、wind里面的资料
http://img2.58codes.com/2024/20163468gxfbPoJnyQ.png
接着加上

从name属性取出城市名称从main属性中取出温度从weather.main中取中天气从weather.main中取出湿度取出风速从updateDate()取时间
<body>    <div id="app">        <h1>天气预报</h1>        <input type="text" v-model="city" @keyup.enter="getWeather">        <button @click="getWeather">获取</button>        <div v-if="weatherData.main">            <h2>{{ weatherData.name }}</h2>            <p>日期: {{ date }}</p>            <p>天气: {{ weatherData.weather[0].main }}</p>            <p>温度: {{ weatherData.main.temp }}°C</p>            <p>湿度: {{ weatherData.main.humidity }}%</p>            <p>风速: {{ weatherData.wind.speed }} m/s</p>        </div>    </div>    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></body></html>

http://img2.58codes.com/2024/20163468SPbfp56Vpl.png


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章