1.Axios介绍:
在实际Vue项目开发过程中,一般都是前后端分离开发,前端UI人员开发Vue,后端服务器人员通过接口向前端人员提供数据,在前后台通信过程中,可以使用Axios组件进行数据的传递,而不用我们自己去写具体的实现。
Axios中文文档:https://www.kancloud.cn/yunye/axios/234845
github地址:https://github.com/axios/axios
2.使用案例:
1).安装:
npm install --save axios |
npm安装很慢,如果安装了cnpm可以使用如下替代:
cnpm install --save axios |
同时建议安装 qs 插件,该插件可以格式化 axios 传递的参数,很好用:
cnpm install --save qs |
2).在 main.js 里面引入加载:
import Axios from "axios" import qs from 'qs' //如果安装了qs,记得引入 Vue.prototype.$axios = Axios |
注:上面我们在引入 axios 之后,将 Axios 配置到了Vue的底层,之后我们用 this.$axios 代表Axios的实例。
3).请求:
①. get请求:
<template> <div> <ul> <li v-for="obj in newsData">{{obj.title}} - {{obj.date}} -{{obj.category}}</li> </ul> </div> </template> <script> export default { name:"Hello", data(){ return { newsData:[] } }, created: function(){ this.$axios("http://www.wwtliu.com/sxtstu/news/juhenews.php",{ params:{ type:"junshi", count:30 } }) .then(function(res) { this.newsData = res.data.result.data; console.log(this.newsData); }.bind(this)) .catch(function(error){ console.log(error); }) } } </script> <style scoped> </style> |
上面等价于:
this.$axios("http://www.wwtliu.com/sxtstu/news/juhenews.php?type=junshi&count=30") .then(res => { this.newsData = res.data.result.data; console.log(this.newsData); }.bind(this)) .catch(error => { console.log(error); }) |
注:在 then() 之后一定要 bind(this),如果不绑定,this将指向axios实例,而不是指向vue实例,执行该句之后将this绑定到vue实例。
②. post请求:
<script> import qs from 'qs' export default { name:"Hello", data(){ return { } }, created: function(){ this.$axios.post("http://www.wwtliu.com/sxtstu/blueberrypai/login.php", qs.stringify({ user_id:"iwen@qq.com", password:"iwen123", verification_code:"crfvw" })) .then(res => { console.log(res.data) }.bind(this)) .catch(error => { console.log(error); }) } } </script> |
说明:
a. form-data转化形式:?name=iwen&age=20
b. x-www-form-urlencoded转化形式:{name:"iwen",age:20}
而 axios 接受的post请求参数的格式是form-data格式,而qs可以将参数自动格式化为form-data格式。
c.在实际开发中,尽量将方法都写到methods里面,如果要在页面打开就执行某个方法,则再在created里面调用一下即可。3.全局的 axios 默认值:
Axios.defaults.baseURL = 'https://api.example.com'; Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; |
4.Axios详解:
方法 | 说明 |
axios.request(config) | 请求 |
axios.get(url[, config]) | GET请求 |
axios.delete(url[, config]) | DELETE请求 |
axios.head(url[, config]) | HEAD请求 |
axios.post(url[, data[, config]]) | POST请求 |
axios.put(url[, data[, config]]) | PUT请求 |
axios.patch(url[, data[, config]]) | PATCH请求 |
axios.all(iterable) | 多个并发执行请求,查看下面例子 |
axios.spread(callback) | 多个并发执行请求,查看下面例子 |
执行多个并发请求案例:
function getUserAccount() { return this.$axios.get('/user/12345'); } function getUserPermissions() { return this.$axios.get('/user/12345/permissions'); } this.$axios.all([getUserAccount(), getUserPermissions()]) .then(this.$axios.spread(function (acct, perms) { // 两个请求现在都执行完成 })); |
5.拦截器:
在 main.js 里面配置拦截器:
// 添加请求拦截器 Axios.interceptors.request.use(function (config) { console.log("此处可以对请求添加拦截"); if(config.method === 'post'){ config.data = qs.stringify(config.data); } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 Axios.interceptors.response.use(function (response) { console.log("此处可以对响应添加拦截"); if(!response.data.success){ return Promise.reject(response); } return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); |
6.跨域处理:
修改 config/index.js 文件,设置代理:
proxyTable: { "/api": { target: "http://10.0.0.206:11666/dmopt/", changeOrigin: true, pathRewrite: { '^/api': '' } } } |
在 main.js 中设置全局属性HOST:
Vue.prototype.HOST = '/api' |
注意:此种跨域解决方案,只能适用于测试阶段,打包的时候,因为没有服务器,所以不能跨域了,此时需要后端解决。解决方案:
①. 可以使用软连接,将前端Vue项目软连到后端项目下。(推荐)
②. 在后端对跨域进行设置。
其他更多使用方法请参看Axios官方文档。