Vue實現天氣預報功能
阿新 • • 發佈:2021-08-28
本文為大家分享了實現天氣預報功能的具體程式碼,供大家參考,具體內容如下
1、功能描述
在搜尋框中輸入城市,下方出現今天及未來四天的天氣情況。搜尋框下面固定了幾個城市,點選可以快速查詢。
2、html程式碼
<div id="app"> <div id="srchbar"> <uPyGqQhkZ;input type="text" v-model="city" @keyup.enter="srch(city)" id="ipt"> <a @click=srch(city) id="btn">search</a> </div> <nav> <a href="#" @click="srch('北京')">北京</a> <a href="#" @click="srch('上海')">上海</a> <a href="#" @click="srch('廣州')">廣州</www.cppcns.coma> <a href="#" @click="srch('深圳')">深圳</a> </nav> <div id="res"> <table> <tr> <th v-for="item in forecasts">{{item.type}}</th> </tr> <tr> <td v-for="item in forecasts">{{item.low}}~{{item.hiuPyGqQhkZgh}}</td> </tr> <tr> <td v-for="item in forecasts">{{item.date}}</td> </tr> </table> </div> </div>
3、程式碼
var app = new Vue({ el: "#app",data: { city: "",forecasts: [] },methods: { srch: function (c) { var that = this; axios.get("http://wthrcdn.etouch.cn/weather_mini?city=" + c).then(function (message) { that.city = c; that.forecasts = message.data.data.forecast; }) } } })
結果示意
總結
主要練習了v-for, v-model,v-on表示式,以及使用axios通過介面請求資料。
小編之前學習過程中曾將收藏了一段關於天氣預報功能的js關鍵程式碼,分享給大家,一起學習。
// 請求地址:http://wthrcdn.etouch.cn/weather_mini
// 請求方法:get,// 請求引數:city(城市名)
// 響應內容:天氣資訊,// 1.點選回車
// 2.查詢資料
// 3.渲染資料
var app = new Vue({
el: '#app',data: {
city: '',weatherList: [],},methods: {
serchWeather: function() {
// console.log('天氣查詢');
// console.log(this.city)
// 呼叫介面
//儲存this
var that = this;
axios.get('http://whttp://www.cppcns.comthrcdn.etouch.cn/weather_mini?city=' + this.city)
.then(function(response) {
console.log(response.data.data.forecast)
that.weatherList = response.data.data.forecast
}).catch(function(err) {})
},changeCity: function(city) {
//1.改城市
//2.查天氣
this.city=city;
this.serchWeather();
}
}
})
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。