Vue学习day04笔记
axios(功能强大的网络请求库)
axios必须先倒入才可以使用
<script src="http://unpkg.com/axios/dist/axios.min.js"></script>
使用get或post方法即可发送对应的请求,then方法中的回调函数会在请求成功或失败时触发,通过回调函数可以获取相应内容或错误信息
axios.get(地址?key=value&key2=value2).then(function(response){},function(err){})
axios.post(地址,key:value,key2:value2).then(function(response){},function(err){})
axios文档:https://github.com/axios/axios
axios+vue
axios回调函数中的this已经改变,无法访问到data中数据,若要使用可先把this保存起来,回调函数中直接调用保存的this即可和本地应用最大的区别就是改变了数据来源。
<div id="app">
<input type="button" value="获取笑话" @click="getjoke">
<p>{{joke}}</p>
</div>
<!--axios在线地址-->
<script src="http://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
/*
接口1:随机笑话
请求地址:https://autumnfish.cn/api/joke
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
*/
var app = new Vue({
el:"#app",
data:{
joke:"很好笑的笑话"
},
methods:{
getjoke:function(){
var that = this;
axios.get("https://autumnfish.cn/api/joke").then
(function(response){
that.joke=response.data;
console.log(response.data)
},function(err){ }
)
}
}
})
</script>
天气查询(网络应用案例)
功能:1.输入城市回车查询。2.点击查询
回车查询包含:按下回车(v-on .enter);查询数据(axios 接口 v-model);渲染数据(v-for 数组 that)
注:应用的逻辑代码建议与页面分离,使用单独的js文件编写,axios回调函数中this指向改变了,需要额外保存一份。服务器返回的数据比较复杂时,获取的时候注意层次结构
点击查询包含:点击城市(v-on 自定义参数);查询数据;渲染数据
<div class="wrap" id="app">
<div class="search_form">
<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">
搜 索
</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.data}}</span></div>
</li>
</ul>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/main.js"></script>
main.js:
var app = new Vue({
el:"#app",
data:{
city:'',
weatherList:[]
},
methods: {
searchWeather:function(){
// console.log('天气查询');
// 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);
console.log(response.data.data.forecast);
that.weatherList = response.data.data.forecast
},function(err){ })
},
changeCity:function(city){
this.city=city;
this.searchWeather();
}
},
})