快速入门Vue第四天:Vue网络应用 axios

网络应用

之前我们学习了vue本地应用,通过vue提供的指令对本地的数据执行操作,但是现在很少有纯本地的应用,或多或少都会进行网络的交互,所以我们来学习vue网络应用,结合网络数据开发。

一、axios

常见的网络请求库,功能单一就是发送请求,容量小,ajax的精封装,可方便地和vue结合。

(1)、axios的基本使用
  • 首先导包:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 导包之后就会注册一个全局的axios对象
  • get请求: axios.get(地址?key=value&key2=value2).then(function(response){},function(err){})
  • post请求:axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})
  • then方法中的回调函数会在请求成功或者失败时触发
  • 通过回调函数的形参可以获取相应内容或错误信息
  • axios官网:https://github.com/axios/axios
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Vue</title>
		<script src="js/vue.js"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		<input type="button" value="get请求" class="get" />
		<input type="button" value="post请求" class="post" />
	<script>
		document.querySelector(".get").onclick = function (){
			axios.get("https://autumnfish.cn/api/joke")
			.then(
				function(response){
					console.log(response);
				},function(err){
					console.log(err);
				}
			)
		}
			</script>
	</body>
</html>

效果如图:
axios获取笑话

(2)、axios+vue的使用

axios如何结合vue开发网络应用

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Vue</title>
		<script src="js/vue.js"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		<div id="app">
			<input type="button" value="获取笑话" @click="getjoke"/>
			<p>{{joke}}</p>
		</div>
	<script>
		var app = new Vue({
			el:"#app",
			data:{
				joke:"一个笑话"
			},
			methods:{
				getjoke:function(){
					var that = this; //进入了axios对象中,vue的原本的this会发生改变,故设之。
					axios.get("https://autumnfish.cn/api/joke")
					.then(
						function(response){
							that.joke = response.data;
						},
						function(err){}
					)
				}
			}
		})
	</script>
	</body>
</html>

效果如图:
笑话效果

  • a x i o s \color{#FF0000}{axios} axios回调函数中的 t h i s \color{#FF0000}{this} this已经改变,无法访问到 d a t a \color{#FF0000}{data} data中数据
  • t h i s \color{#FF0000}{this} this保存起来,回调函数中直接使用保存的 t h i s \color{#FF0000}{this} this即可
  • 和本地应用的最大区别就是改变了 数 据 来 源 \color{#FF0000}{数据来源}

二、axios 查天气

结合vue的知识利用axios做一个查询天气的网站,能够做到点击查询和输入回车查询
天知道

(1)、回车查询

按下回车(v-on .enter)、查询数据(anxios 接口 v-model)、渲染数据(v-for 数组 that)

  • 应用的逻辑代码建议和页面 分 离 \color{#FF0000}{分离}
  • a x i o s \color{#FF0000}{axios} axios回调函数中的this指向改变了,需要额外的保存一份
  • 服务器返回的数据比较复杂时,获取的时候需要注意层级结构
(2)、点击查询

点击城市(v-on 自定义参数)、查询数据( this.方法() )、渲染数据

如图所示:
点击查询

  • 自定义参数可以让代码的 复 用 性 \color{#FF0000}{复用性} 更高
  • m e t h o d s \color{#FF0000}{methods} methods中定义的方法内部,可以通过 t h i s \color{#FF0000}{this} this关键字点出其他方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值