Vue之Axios 网络请求库
- 一、Axios 网络请求库
- 1、简介
- 2、Axios 下载安装
- 3、Axios 基本使用
- 二、Axios & Vue
- 1、get
- 2、post
- 3、案例
一、Axios 网络请求库
1、简介
说到axios我们就不得不说下Ajax。在旧浏览器页面在向服务器请求数据时,因为返回的是整个页面的数据,页面都会强制刷新一下,这对于用户来讲并不是很友好。并且我们只是需要修改页面的部分数据,但是从服务器端发送的却是整个页面的数据,十分消耗网络资源。而我们只是需要修改页面的部分数据,也希望不刷新页面,因此异步网络请求就应运而生。Ajax(Asynchronous JavaScript and XML)
- 异步网络请求,Ajax能够让页面无刷新的请求数据。
- 实现ajax的方式有多种,如jQuery封装的ajax,原生的XMLHttpRequest,以及axios。
- 但各种方式都有利弊:
- 原生的XMLHttpRequest的配置和调用方式都很繁琐,实现异步请求十分麻烦
- jQuery的ajax相对于原生的ajax是非常好用的,但是没有必要因为要用ajax异步网络请求而引用jQuery框架
Axios(ajax i/o system)
这不是一种新技术,本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。具备以下特点:
- 在浏览器中创建XMLHttpRequest请求
- 在node.js中发送http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消要求
- 自动转换JSON数据
- 客户端支持防止CSRF/XSRF(跨域请求伪造)
2、Axios 下载安装
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
3、Axios 基本使用
-
get
:获取数据,请求指定的信息,返回实体对象 -
post
:向指定资源提交数据(例如表单提交或文件上传) -
put
:更新数据,从客户端向服务器传送的数据取代指定的文档的内容 -
patch
:更新数据,是对put方法的补充,用来对已知资源进行局部更新 -
delete
:请求服务器删除指定的数据
get
、post
请求基本语法:
<!-- get 形式传递参数使用 ?拼接 -->
axios.get(地址?key1=value&key2=values).then(function(response){},function(err){})
<!-- post 形式传递参数为一个对象 -->
axios.post(地址,{key:value,key2:value2}).then(function(response){},function(err){})
语法中的 then(function(response){},function(err){})
包含了两部分内容分别表示请求成功、失败时的处理方式。就拿上面的代码来说,当请求成功的时候将请求获取的对象信息在控制台输出;当请求失败的时候,将错误内容在控制台输出:post
请求模拟的是用户注册,当注册过后返回的对象中的data
信息为“已被注册,请检查”,反之 “注册成功”:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- <script src="https://unpkg.com/vue@next"></script> -->
<!-- 官网提供的 axios 在线地址 -->
<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>
/*
接口1:随机笑话
请求地址:https://autumnfish.cn/api/joke/list
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
*/
document.querySelector('.get').onclick = function () {
// get 形式传递参数使用 ?拼接
axios.get("https://autumnfish.cn/api/joke/list?num=3")
.then(function (response) {
// 控制台打印输出获取的响应对象的信息
console.log(response);
}, function (err) {
// 控制台打印输出请求失败的信息
console.log(err);
})
}
/*
接口2:用户注册
请求地址:https://autumnfish.cn/api/user/reg
请求方法:post
请求参数:username(用户名,字符串)
响应内容:注册成功或失败
*/
document.querySelector('.post').onclick = function () {
// post 形式传递参数为一个对象
axios.post("https://autumnfish.cn/api/user/reg", { username: "jack" })
.then(function (response) {
// 控制台打印输出获取的响应对象的信息
console.log(response);
}, function (err) {
// 控制台打印输出请求失败的信息
console.log(err);
})
}
</script>
</body>
</html>
总结
- post 形式传递参数为一个对象
- 使用get、post等方法即可发送对应的请求
- then方法中的回调函数会在请求成功或失败时触发
- 通过回调函数的形参可以获取响应内容,或错误信息
二、Axios & Vue
1、get
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入 axios、vue -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="../other/vue.js"></script>
</head>
<body>
<div id="app1">
<button @click="getJoke">getJoke</button>
<p>{{joke1}}</p>
</div>
<br>
</body>
<script>
var app1 = new Vue({
el: "#app1",
data: {
joke1: "初始值",
},
methods: {
getJoke: function () {
// 暂时存储外部的 this 对象
var tmp = this;
axios.get("https://autumnfish.cn/api/joke").then(function (response) {
tmp.joke1 = response.data;
}, function (err) {
tmp.joke1 = response.data;
})
}
}
})
</script>
</html>
特别注意:关于回调函数中的 this 对象中间存储的问题!
- axios回调函数中的this已经改变,无法访问到data中数据
- 把this保存起来,回调函数中直接使用保存的this即可
- 和本地应用的最大区别就是改变了数据来源
2、post
第一种使用v-model双向绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入 axios、vue -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="../other/vue.js"></script>
</head>
<body>
<div id="app">
<input placeholder="输入注册名称后回车" v-model='username' @keyup.enter="select" />
<br>
<p>{{msg}}</p>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
msg: '',
username: '',
},
methods: {
select: function () {
var that = this;
axios.post("https://autumnfish.cn/api/user/reg", { username: that.username })
.then(function (response) {
// 控制台打印输出获取的响应对象的信息
that.msg = response.data
console.log(response.data)
}, function (err) {
// 控制台打印输出请求失败的信息
that.msg = response
})
}
}
})
</script>
</html>
第二种
数据的双向绑定还可以用另外一种方式实现,也就是通过v-bind指令和v-on指令。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入 axios、vue -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="../other/vue.js"></script>
</head>
<body>
<div id="app">
<input placeholder="输入注册名称" :value="username" @keyup.enter="select" />
<br>
<p>{{msg}}</p>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
msg: '',
username: '',
},
methods: {
select: function (event) {
var that = this;
this.username = event.target.value;
axios.post("https://autumnfish.cn/api/user/reg", { username: that.username })
.then(function (response) {
// 控制台打印输出获取的响应对象的信息
that.msg = response.data
console.log(response.data)
}, function (err) {
// 控制台打印输出请求失败的信息
that.msg = response
console.log(response)
})
}
}
})
</script>
</html>
第三种
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入 axios、vue -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="../other/vue.js"></script>
</head>
<body>
<div id="app">
<input placeholder="输入注册名称" ref="son" />
<button @click="select">按钮</button>
<br>
<p>{{msg}}</p>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
msg: '',
username: '',
},
methods: {
select: function () {
var that = this;
// 我想按下button时把input的username传到app.username中
console.log(this.$refs.son.value)
this.username = this.$refs.son.value
axios.post("https://autumnfish.cn/api/user/reg", { username: that.username })
.then(function (response) {
// 控制台打印输出获取的响应对象的信息
that.msg = response.data
console.log(response.data)
}, function (err) {
// 控制台打印输出请求失败的信息
that.msg = response
console.log(response)
})
}
}
})
</script>
</html>
3、案例
- 我们通过
v-model='city'
双向绑定 city 数据, - 通过对城市请求的数据结构分析,前期真正数据被封装在
response.data.data.forecast
中,并且是一个长度为 5 的Array
,表示 5天的天气信息,所以我们最终应当获取到forecast
下的数据进行存储,后面用于界面的展示。 - 根据上面分析的天气数据结构,我们通过
v-for="item in weatherList"
循环展示 5 天的部分数据信息,对应的数据信息通过item
属性 的方式获取。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 导入 axios、vue -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="../other/vue.js"></script>
</head>
<body>
<div id="app">
<input placeholder="请输入查询的天气" v-model='city' @keyup.enter="searchWeather" />
<br>
<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>
</body>
<script src="./demo2.js"></script>
</html>
var app = new Vue({
el: "#app",
data: {
city: '',
weatherList: ''
},
methods: {
searchWeather: function () {
var that = this;
axios.get('http://wthrcdn.etouch.cn/weather_mini?city=' + this.city)
.then(function (response) {
that.weatherList = response.data.data.forecast
}, function (error) {
console.log(error)
})
}
}
})