用户可以输入城市名称,然后点击按钮来获取天气讯息。当用户输入城市名称并点击按钮时,应用会向天气API发送请求,然后显示返回的天气数据
首先先到openweathermap.org的网站看一下我们要用的api
<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里面的资料
接着加上
<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>