一、输入查询 1.按下回车(v-on,enter) 2.查询数据(axios 接口 v-model) 3.渲染数据(v-for 数组 that)
应用的逻辑代码建议和页面分离,使用单独的js文件编写 axios回调函数中this指向改变了,需要额外的保存一份 服务器返回的数据比较复杂时,获取的时候需要注意层级结构
二、点击查询 1.点击城市(v-on 自定义参数) 2.查询数据 3.渲染数据
自定义参数可以让代码的复用性更高 methods中定义的方法内部,可以通过this关键字点出其他的方法
html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>天气预报</title> <script src="vue.js" type="text/javascript" charset="UTF-8"></script> <script src="axios.min.js"></script> </head> <body> <div id="app"> <!-- 查询模块 --> <div class="search_form"> <input type="text" @keyup.enter="searchWeather" v-model="city" placeholder="请输入查询的天气" class="input_txt" /> <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> <!-- 查询结果展示 --> <ul class="weather_list"> <!-- 每天的预报情况 --> <li v-for="item in weatherList"> <div> <span> {{item.type}}</span> <div> <b>{{item.low}}</b> <b>{{item.high}}</b> </div> <div> <span>{{item.date}}</span> </div> </div> </li> </ul> </div> <!-- 自己的js --> <script src="./WeatherForecastMainjs.js"></script> </body> </html>JS:
/* 请求地址:http://wthrcdn.etouch.cn/weather_mini 请求方法:get 请求参数:city(城市名) 响应内容:天气信息 1.点击回车 2.查询数据 3.渲染数据 */ var app = new Vue({ el:"#app", data:{ city:'', weatherList:[], }, methods:{ searchWeather:function(){ // console.log(this.city); // 保存this var that = this; //调用接口 axios.get('http://wthrcdn.etouch.cn/weather_mini?city='+this.city) .then(function(response){ console.log(response.data.data.forecast); that.weatherList = response.data.data.forecast; }, function(err){ console.log(err); }) .catch(function(err){ console.log(err); }) }, changeCity:function(city){ this.city = city; this.searchWeather(); } }, })