Axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
Features
1、从浏览器中创建 XMLHttpRequests
2、从 node.js 创建 http 请求
3、支持 Promise API
4、拦截请求和响应
5、转换请求数据和响应数据
6、取消请求
7、自动转换 JSON 数据
8、客户端支持防御 XSRF
导入Axios包
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios.get应用
//为get类的button添加点击事件,事件作用为获取特定url的信息
document.querySelector(".get").onclick = function () {//回调函数
axios.get("https://autumnfish.cn/api/joke/list?num=3")//url
.then(function (response) {
console.log(response)//获取成功执行的操作
}, function (err) {
console.log(err)//获取失败执行的操作
}
)
}
axios.post应用
//为post类的button添加点击事件,将post中字典的信息上传服务器
document.querySelector(".post").onclick = function () {
axios.post("https://autumnfish.cn/api/user/reg", { username: "FJf" })
//url, 上传信息字典
.then(function (response) {
console.log(response)
}, function (err) {
console.log(err)
})
}
axios配合vue使用
天知道
在js文件中定义vue实例,通过vue实时将数据渲染到dom上,在vue实例中,我们要去获取服务器中的数据,并将服务器中的数据返回到我们的实例中去,代码如下:
var app = new Vue({
el: "#app",
data: {
city: "",//用于存储输入栏的城市信息 v-model
weatherList: []//用于存储服务器返回的天气数组
},
methods: {
searchWeather: function () {
//保存this
var that = this
axios.get("http://wthrcdn.etouch.cn/weather_mini?city=" + this.city).then(//"。。。?city="+ this.city 增加返回的条件
function (response) {
console.log(response.data.data.forecast)//获取response中对应的天气数组
that.weatherList = response.data.data.forecast//返回天气数组到weatherlist中
}
).catch(function (err) { })
}
}
})
获取到我们数据之后,我们需要将数据实时的渲染到dom上去,为此使用v-for去循环创建li,使用插值表达式进行插值。核心代码如下:
</div>
<ul class="weather_list">
<li v-for="items in weatherList">
<div class="info_type"><span class="iconfont">{{ items.type }}</span></div>
<div class="info_temp">
<b>{{ items.low }}</b>
~
<b>{{ items.high }}</b>
</div>
<div class="info_date"><span>{{ items.date }}</span></div>
</li>
</ul>
</div>
天知道——点击查询
因为vue的信息是实时响应的,我们只需要将vue实例中的数据改变,就可以响应到dom上,同时使用回车查询时的函数通过服务器获取数据即可以完成。
vue
getCity: function (city) {
this.city = city//根据点击事件调整city的值
this.searchWeather()//根据city的值获取服务器数据并同步渲染
}
html
<div class="hotkey">
<a href="javascript:;" @click="getCity('开平')">开平</a> <!-- 使用自义定getCity函数更改city的值 -->
<a href="javascript:;" @click="getCity('佛山')">佛山</a>
<a href="javascript:;" @click="getCity('广州')">广州</a>
<a href="javascript:;" @click="getCity('深圳')">深圳</a>
</div>
摘自:https://www.bilibili.com/video/BV12J411m7MG?p=29