天知道-网络应用-Vue小案例-黑马程序员
生活随笔
收集整理的這篇文章主要介紹了
天知道-网络应用-Vue小案例-黑马程序员
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
案例介紹
學習背景:快快學習,學完找工作
輸入城市回車或點擊搜索可以查詢天氣。
代碼結構
<div class="wrap" id="app"><div class="search_form">//logo和搜索欄<div class="logo"><img src="img/logo.png" alt="logo" /></div><div class="form_group"><input type="text" v-model="city" @keyup.enter="searchWeather" class="input_txt" placeholder="請輸入查詢天氣的城市"/><button class="input_sub" @click="searchWeather">搜 索</button></div>//熱門城市快捷搜索<div class="hotkey"><a href="javascript:;" @click="changeCity('北京')">北京</a><a href="javascript:;" @click="changeCity('上海')">上海</a><a href="javascript:;" @click="changeCity('廣州')">廣州</a><a href="javascript:;" @click="changeCity('深圳')">深圳</a></div></div>//顯示天氣的格式<ul class="weather_list"><li v-for="item in weatherList"><div class="info_type"><span class="iconfont">{{ item.type }}</span></div><div class="info_temp"><b>{{ item.low }}</b>~<b>{{ item.high }}</b></div><div class="info_date"><span>{{ item.date }}</span></div></li></ul></div>js部分:
var app = new Vue({el:"#app",data:{city:"無錫",weatherList:[]},methods:{searchWeather:function(){// console.log("search");// console.log(this.city);// 保存thisvar that = this;axios.get('http://wthrcdn.etouch.cn/weather_mini?city='+this.city)// 成功之后調取.then(function(response){// console.log(response);// console.log(response.data.data.forecast);// 這里就直接是that.weatherList而不是that.data.weatherList// 還要注意:調用此函數的是服務器端,所這里的this不是Vue中的thisthat.weatherList=response.data.data.forecast// app.weatherList=response.data.data.forecast})// // 箭頭函數方式// .then(response => {// this.weatherList = response.data.data.forecast// })// 失敗之后調取.catch(function(err){})},changeCity:function(city){this.city=city;this.searchWeather();}}})分析
請求地址:http://wthrcdn.etouch.cn/weather_mini
請求方法:get
請求參數:city(城市名)
響應內容:天氣信息
通過接口發送請求,接收返回的信息展示
知識點學習
axios.get('http://wthrcdn.etouch.cn/weather_mini?city='+this.city)里面?city=是原鏈接后加的,又加了this.city的值,只要括號里是一個完整的鏈接就行。
其中javascript:是偽協議,它可以讓我們通過一個鏈接來調用javascript函數.而采用這個方式 javascript:可以實現A標簽的點擊事件運行時,如果頁面內容很多,有滾動條時,頁面不會亂跳,用戶體驗更好
解決這個問題可以提前保存一份this,或者用app.weatherList,又或者用箭頭函數。箭頭函數我也不是很了解,至于為什么this 會不一樣,我覺得應該是this指的是本地,當axios請求到服務端時,this就已經是服務端的地址了,然后.then是在服務端執行的,所以其中的this自然是指服務端的this。不知道理解的對不對。
注意事項
保存this 時,要注意在axios外保存。
項目再現
代碼地址:GitHub
總結
以上是生活随笔為你收集整理的天知道-网络应用-Vue小案例-黑马程序员的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(2966):上午回顾
- 下一篇: 小程序卡片叠层切换卡片_现在,卡片和清单