Axios插件 是一个基于 promise 的 HTTP 库,可以用在浏览器、node.js、react.js下使用。
它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
1.axios的安装
npm install --save axios
2.axios的使用
使用axios共有如下两种方法:
①哪里使用,在哪里引入
<template>
<div id="app">
{{info}}
</div>
</template>
<script>
import axios from 'axios' //1.组件中引入,每个组件使用,每个组件就都得引入
export default {
name: 'App',
data() {
return{
info:''
}
},
mounted(){//2.组件中使用
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response))
}
}
</script>
<style scoped>
#app {
text-align: center;
}
</style>
②在main.js中引入
因为axios并不是一个组件,所以不能使用Vue.use(...)方法将其引入项目,所以只能在每个需要发送请求的组件中即时引入。为了解决这个问题,我们在引入 axios 之后,通过修改原型链,来更方便的使用。
import Vue from 'vue'
import App from './App'
import router from './router/index'
import store from './vuex/store'
import axios from 'axios'//1.引入axios
Vue.prototype.axios = axios; //2.修改原型链
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
})
接下来你便可以再组件中,通过this.axios.get('xxx') .then(response => (xxx))来使用了
<template>
<div id="app">
<img src="./assets/logo.png">
{{info}}
</div>
</template>
<script>
export default {
name: 'App',
data() {
return{
info:''
}
},
mounted(){ //修改原型链后,此处直接通过this.axios即可使用
this.axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response))
}
}
</script>
<style scoped>
#app {
text-align: center;
}
</style>
3.axios错误处理
很多时候我们可能并没有从 API 获取想要的数据。这可能是由于很多种因素引起的,比如 axios 调用可能由于多种原因而失败,包括但不限于:
- API 不工作了;
- 请求发错了;
- API 没有按我们预期的格式返回信息。
当发送这个请求的时候,我们应该检查一下这些情况,并在所有情况下都返回相应的信息以便处理这些问题。在 axios 中,我们会通过使用catch来做这件事,这样我们就会知道在请求 API 的过程中是否有地方出错了。
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response.data.bpi))
.catch(error => console.log(error))
4.axios执行get请求、post请求、执行多个并发请求
执行Get请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行POST请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个并发请求
//请求A
function getUserAccount() {
return axios.get('/user/12345');
}
//请求B
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
5.向$.ajax一样,可以通过向 axios
传递相关配置来创建请求
发送POST请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
发送GET请求(默认的方法)
axios('/user/12345');
6.axios请求数据长时间没有加载出来,如何处理
当数据长时间生成不出来或 API 不工作的时候会怎样呢?现在用户将会什么都看不到。我们可能想为这种情况构建一个加载效果,然后在根本无法获取数据时通知用户。
new Vue({
el: '#app',
data () {
return {
info: null,
loading: true,//加载中状态
errored: false//是否错误标识
}
},
filters: {
currencydecimal (value) {
return value.toFixed(2)
}
},
mounted () {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
this.info = response.data.bpi
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
})
<div id="app">
<h1>Bitcoin Price Index</h1>
<section v-if="errored">
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
</section>
<section v-else>
<div v-if="loading">Loading...</div>
<div
v-else
v-for="currency in info"
class="currency"
>
{{ currency.description }}:
<span class="lighten">
<span v-html="currency.symbol"></span>
{{ currency.rate_float | currencydecimal }}
</span>
</div>
</section>
</div>
我们还可以做进一步优化,如用组件来实现不同部分、给出更明确的错误报告。这都取决于你使用的 API 以及应用的复杂度。
其他更多关于axios,请参见:
①github地址:https://github.com/axios/axios
②中文版地址:https://www.kancloud.cn/yunye/axios/234845
估计这也是Vue学习的最后一个模块总结了,当初答应自己必须努力学会Vue,给自己来个小小的鼓励,Vue知识部分到此大致就完毕了。
附:Vue篇目录:
3.Vue.js 实战 调查问卷WebApp项目 4.vue-cli + webpack搭建Vue开发环境
5. Vue简单问题汇总(持续更新...) 6.Vue组件之间数据通信之Bus总线
7.Vue-Router导航钩子(附Demo实例) 8.ES6箭头函数与普通函数的区别
9.Vuex的使用 10.Vuex组件中的mapState、mapGetters、mapMutations、mapActions等辅助函数
11.组件中调用Vuex的state,getters,mutations,actions,modules的数据传递、传参问题