Vue快速入门篇(二)


网络应用

Vue结合网络数据开发应用

axios的基本使用

1、axios必须先导入才可以使用
2、使用get或post方法即可发送对应的请求
3、then方法中的回调函数会在请求成功或失败时触发
4、通过回调函数的形参可以获取响应内容,或错误信息

导入axios:


语法:
axios.get(地址?key=value&key2=values).then(function(response){},function(err){})

axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})

以下提供两个测试接口:

接口1:随机笑话
	请求地址:https://autumnfish.cn/api/joke/list
	请求方法:get
	请求参数:num(笑话条数)
	响应内容:随机笑话
	
接口2:用户注册
	请求地址:https://autumnfish.cn/api/user/reg
	请求方法:post
	请求参数:username(用户名)
	响应内容:注册成功

测试代码


    
    
    

    
     

axios+vue

axios结合vue开发网络应用

提供一个测试接口:

随机获取笑话的接口
	请求地址:https://autumnfish.cn/api/joke
	请求方法:get
	请求参数:无
	响应内容:一条随机笑话
	

    

{{joke}}

效果:

小结:

  • axios回调函数中的this已经改变,无法访问到data中的数据
  • 把this保存起来,回调函数中直接使用保存的this即可
  • 和本地应用的最大区别就是改变了数据来源

天气预报案例


    
  • {{item.type}}
    {{item.low}} ~ {{item.high}}
    {{item.date}}
//js文件 /* 请求地址:http://wthrcdn.etouch.cn/weather_mini 请求方法:get 请求参数:city 1、点击回车 2、查询数据 3、渲染数据 */ var app = new Vue({ el:"#app", data:{ city:'', weaterList:[] }, methods:{ searchWeater:function(){ var that = this; //查询天气 axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city).then(function(response){ //console.log(response.data) that.weaterList = response.data.data.forecast console.log(that.weaterList) },function(err){ }) }, changeCity:function(city){ this.city = city; this.searchWeater(); } } })

效果: