最近在项目中需要用到axios,所以就恶补一下这个axios到底是什么东东。越来它是vue-resource的替代品,官网也说了,以后都用axios,
vue-resource不在维护。那么这个axios怎么用呢,上网搜索了一大堆,基本上都是雷同,我也不知道那些作者有没有在本地测试过。至少我按照网上的做法,总不能成功。经过几天的奋斗,我终于把它搞清楚了,为了不让其他的小伙伴们走弯路,我把我在实际操作中的例子分享给大家,希望对大家有用。
一、安装axios
老规矩,要想使用axios,我们得安装它,安装方式:npm install axios
二、客户端使用方式
先来看看网上的答案,如图所示,我已经在图上标识过了,这种做法是错误的。

正确的做法是去掉post,如图所示:


三、服务器端设置
虽然客户端跨域设置好了,但是你还是不能访问接口数据,必须在服务器端设置header属性,如图所示:

四、axios方法封装
一般情况下,我们会用到的方法有:GET,POST,PUT,PATCH,封装方法如下:


五、封装后的方法的使用
1、在main.js文件里引用之前写好的文件,我的命名为http.js

2、在需要的地方之间调用,如图所示:

说明:
GET调用方法如下,其中url是接口地址
this.$get(url).then((res) {
//代码
});
POST调用方法如下,其中url是接口地址,data是请求的数据。
this.$post(url,data).then({
//代码
});
PATCH调用方法如下,其中url是接口地址,data是请求的数据
this.$patch(url,data).then({
//代码
});
PUT调用方法如下,其中url是接口地址,data是请求的数据
this.$put(url,data).then({
//代码
});
看了以上内容,是不是很简单,其实也没啥的,但是就是这个问题卡了我好久,在看看网上的答案,真的是不堪一击。问题解决了,内心真的好激动啊 O(∩_∩)O哈!
作者:陈楠酒肆
链接:http://www.jianshu.com/p/3b5e453f54f5
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。