安装axios cnpm i axios --save
有三中请求方式:
1.get请求
get:function () { axios.get('package.json',{ params:{ userId:"chen" }, headers:{ token:"chen123" } }).then(res=>{ this.msg = res.data }).catch(function (error) { console.log("error init" + error) }) }
2.post请求
post:function () { axios.post("package.json",{ userId:"chen456" },{ headers:{ token:"chen111" } }).then(res=>{ this.msg = res.data }).catch(function (error) { }) }
3.自行配置
http:function () { axios({ url:'package.json', method:"get", //pos data, get params将参数传过去 data:{ userId:"123chen" }, params:{ userId:"345chen" }, headers:{ token:"chen" } }).then(res=>{ this.msg = res.data; }) } }
请求方式有两种:post,get。两者的区别:
post的参数通过data获取,但不传到路径中http://localhost:8080/Imooc/ImoocMall/package.json
get方式参数通过params获取,并将参数?加参数的方式传递到路径中http://localhost:8080/Imooc/ImoocMall/package.json?userId=345chen。
4.全局拦截器
/ 发送请求 axios.interceptors.request.use(function (config) { console.log('request init') return config }) // 响应 axios.interceptors.response.use(function (response) { console.log("respone init") return response; })
发送请求的时候如果页面内容无法快速加载出来,可以用 axios.interceptors.request.use()这种方式添加图片预加载/loading
响应后如果有其他需求可以用axios.interceptors.response.use()处理。