---恢复内容开始---
1、Axios
1)基于promise的HTTP库,可用在浏览器或nodejs中
2)使用方法:
在模块内使用需要挂载到Vue对象上:
Vue.prototype.$axios=axios
然后通过this.$axios来使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./node_modules/vue/dist/vue.js"></script> <script src="./node_modules/vue-router/dist/vue-router.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> </head> <body> <div id="app"> </div> </body> <script> let App = {//将组件状态放 template: `<div> hello </div>`, created() { console.log(this.$axios) } } Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App }, }) </script> </html>
简单地使用axios发送get请求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { template:` <div> <button @click = 'sendAjax'>发请求</button> </div> `, methods:{ sendAjax(){ this.$axios.get('http://127.0.0.1:8888/') .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el:'#app', template:`<App />`, components:{ App } }); </script> </body> </html>
axios.all()方法执行并发请求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data(){ return { res1:"", res2:'' } }, template:` <div> 响应1:{{res1}} 响应2:{{res2}} <button @click = 'sendAjax'>合并强求</button> </div> `, methods:{ sendAjax(){ // 请求1 get: / // 请求 post : /add this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var q1 = this.$axios.get(''); var q2 = this.$axios.post('add','a=1'); this.$axios.all([q1,q2]) .then(this.$axios.spread((res1,res2)=>{ // 全部成功了 this.res1 = res1.data; this.res2 = res2.data; })) .catch(err=>{ // 其一失败 console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el:'#app', template:`<App />`, components:{ App } }); </script> </body> </html>
合并请求,并发处理:axios.all()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data(){ return { res1:"", res2:'' } }, template:` <div> 响应1:{{res1}} 响应2:{{res2}} <button @click = 'sendAjax'>合并强求</button> </div> `, methods:{ sendAjax(){ // 请求1 get: / // 请求 post : /add this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';//设置公共的请求url地址 var q1 = this.$axios.get(''); var q2 = this.$axios.post('add','a=1'); this.$axios.all([q1,q2]) .then(this.$axios.spread((res1,res2)=>{ // 全部成功了 this.res1 = res1.data; this.res2 = res2.data; })) .catch(err=>{ // 其一失败 console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el:'#app', template:`<App />`, components:{ App } }); </script> </body> </html>
也可以通过向axios传递相关配置来创建请求 axios({config})
axios的option 配置选项:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { template: ` <div> <button @click = 'sendAjax'>发请求</button> </div> `, methods: { sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/' this.$axios.get('', { params: { id: 1 }, // 在传递给then/catch之前,允许修改响应的数据 transformResponse: [function(data) { // 对 data 进行任意转换处理 // console.log(data); // console.log(typeof data); data = JSON.parse(data); console.log(data); return data; }] }) .then(res => { console.log(res.data.msg); }) .catch(err => { console.log(err); }) this.$axios.post('/add', { firstName: 'Fred' }, { // `transformRequest` 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [function(data) { // 对 data 进行任意转换处理 console.log(data); return data; }], }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
使用aixos进行文件的上传:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { file: {}, rate:0 } }, template: ` <div> 上传进度:{{rate}}% 选择文件: <input type="file" name = 'file' @change = 'changeHandler'/> <button @click='sendAjax'>发送请求</button> </div> `, methods: { sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var fd = new FormData(); fd.append('file', this.file); this.$axios.post('upload', fd, { onUploadProgress: (progressEvent)=> { // 对原生进度事件的处理 console.log(progressEvent); var progress = (progressEvent.loaded/progressEvent.total)*100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); }) }, changeHandler(e) { console.log(e.target.files[0]); this.file = e.target.files[0]; } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
取消请求:
cancel token
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { file: {}, rate: 0, source: null, currengtLoaded: 0 } }, template: ` <div> 上传进度:{{rate}}% 选择文件: <input type="file" name = 'file' @change = 'changeHandler'/> <button @click='sendAjax'>发送请求</button> <button @click = 'cancel'>取消请求</button> <button @click = 'resume'>续传</button> </div> `, methods: { resume() {//断点续传功能 var fileData = this.file.slice(this.currengtLoaded,this.file.size); var fd = new FormData(); fd.append('file', fileData); this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var CancelToken = this.$axios.CancelToken; var source = CancelToken.source(); this.source = source; this.$axios.post('upload', fd, { // 携带取消标识 cancelToken: source.token, onUploadProgress: (progressEvent) => { // 对原生进度事件的处理 console.log(progressEvent); this.currengtLoaded += progressEvent.loaded; var progress = (this.currengtLoaded / progressEvent.total) * 100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) }, cancel() { this.source.cancel('请求被取消'); }, sendAjax() { this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; var CancelToken = this.$axios.CancelToken; var source = CancelToken.source(); this.source = source; var fd = new FormData(); fd.append('file', this.file); this.$axios.post('upload', fd, { // 携带取消标识 cancelToken: source.token, onUploadProgress: (progressEvent) => { // 对原生进度事件的处理 console.log(progressEvent); this.currengtLoaded = progressEvent.loaded; var progress = (progressEvent.loaded / progressEvent.total) * 100; console.log(progress); this.$nextTick(function() { this.rate = Math.ceil(progress); }) } }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }) }, changeHandler(e) { console.log(e.target.files[0]); this.file = e.target.files[0]; } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>
拦截器:在请求被then或catch响应之前拦截它们
this.axios.intercepters
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .spinner { margin: 100px auto; 50px; height: 60px; text-align: center; font-size: 10px; } .spinner>div { background-color: #67CF22; height: 100%; 6px; display: inline-block; -webkit-animation: stretchdelay 1.2s infinite ease-in-out; animation: stretchdelay 1.2s infinite ease-in-out; } .spinner .rect2 { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .spinner .rect3 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } .spinner .rect4 { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .spinner .rect5 { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } @-webkit-keyframes stretchdelay { 0%, 40%, 100% { -webkit-transform: scaleY(0.4) } 20% { -webkit-transform: scaleY(1.0) } } @keyframes stretchdelay { 0%, 40%, 100% { transform: scaleY(0.4); -webkit-transform: scaleY(0.4); } 20% { transform: scaleY(1.0); -webkit-transform: scaleY(1.0); } } </style> </head> <body> <div id="app"> </div> <script type="text/javascript" src="./vue.min.js"></script> <script src="./node_modules/axios/dist/axios.js"></script> <script type="text/javascript"> var App = { data() { return { isShow: false } }, template: ` <div> <div class="spinner" v-show = 'isShow'> <div class="rect1"></div> <div class="rect2"></div> <div class="rect3"></div> <div class="rect4"></div> <div class="rect5"></div> </div> <button @click = 'sendAjax'>发请求</button> </div> `, methods: { sendAjax() { //实现一个类似cookie的机制 // // 添加请求拦截器 this.$axios.interceptors.request.use((config)=> { console.log(config); // 在发送请求之前做些什么 var token = localStorage.getItem('token'); if (token) { config.headers['token'] = token; } this.isShow = true; return config; }, function(error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器,类似中间件的处理 this.$axios.interceptors.response.use((response) =>{ // 对响应数据做点什么 console.log(response.data.token); if (response.data.token) { localStorage.setItem('token', response.data.token); } this.isShow = false; return response; }, function(error) { // 对响应错误做点什么 return Promise.reject(error); }); this.$axios.get('http://127.0.0.1:8888/') .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); }) } } }; Vue.prototype.$axios = axios new Vue({ el: '#app', template: `<App />`, components: { App } }); </script> </body> </html>