既然官方已经说了不在维护vue-resource,那咱们就看看axios是怎么使用的..........php
1)get方法的使用html
axios.get
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios的初步使用</title> <script src="../lib/vue.js"></script> <script src="../lib/axios.min.js"></script> </head> <body> <div id="app"> <my-f1></my-f1> </div> </body> </html> <script> const c1={ template:` <div v-if="userList.length"> <ul> <li v-for="item in userList">{{item.id}}</li> </ul> </div> `, props:{}, data(){ return { userList:['fd','rr','tt'], } }, mounted(){ this.getList(); }, computed:{ user(){ return this.usersList; } }, methods:{ getList(){ const self=this; axios.get('../data/a1.php',{params:{ id:2 }}).then(function(res){ self.userList=res.data; }).catch(function(res){ console.log(res); }); }, } }; const myVue = new Vue({ el:'#app', components:{ myF1:c1 }, }); </script>
a1.php前端
<?php header("Content-Type:application/json;charset=UTF8"); $myDB= new PDO('mysql:host=127.0.0.1;dbname=axiox;port=3307','root',''); $id=$_GET['id']; // $fname=$_POST['firstname']; // $lname=$_POST['lastname']; // $body = @file_get_contents('php://input'); // echo $fname ; if($myDB){ $res= $myDB->query("select * from stu"); while($row = $res->fetch( PDO::FETCH_ASSOC)){ // print_r($row); $arr[]=$row; } } else{ die("fali"); } // json_encode($arr); print_r( json_encode($arr)); ?>
以上很简单的一个例子。。。。vue
咱们注意一下请求头的content-typemysql
2)使用post请求ios
axios.post
当你使用post请求的时候,好像会有一点问题。。。。。
axios.post('../data/a1.php', {//后端就不能使用$_post['']接受参数了,后端要接受请求主体
name:'士大夫', age:33 }) .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); });
php:sql
$fname=$_POST['name'];
结果:json
好像获取不到请求传递的值......axios
可是办法仍是有的,这个时候咱们能够在后端(这里使用的是php),来获取整个请求主体....后端
$body = @file_get_contents('php://input');
但仍是很奇怪,为啥????
看看官方的解释.................
而后我就试试....
getList(){ const self=this; //这里咱们不修改请求头,而是修改 userService(手动将post请求参数变为get请求形式,后端可使用$_POST['参数名'],接受参数) let param = new URLSearchParams(); param.append("firstname", "Fred"); param.append("lastname", "Flintstone"); axios.post('../data/a1.php',param) .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); }); },
php接受参数;(很明显我前端作了参数处理)
$fname=$_POST['firstname']; echo $fname;
很明显的发现咱们如今的请求方式变为:
axios.post('../data/a2.php', { name:'tom', age:33, id:'wodo id shi 222' }) .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); });
后端:
$body = @file_get_contents('php://input');//接受整个请求主体 $body=json_decode($body) ;//反序列化 $id=$body->id;//获取欲取参数 echo $id;
进一步拓展:
https://www.lvtao.net/dev/1179.html
<script> const c1={ template:` <div v-if="userList.length"> <ul> <li v-for="item in userList">{{item.id}}</li> <p>this is tea ifno : <table> <tr> <td>id</td> <td>name</td> <td>salary</td> <td>address</td> </tr> <tr> <td>{{tea.id}}</td> <td>{{tea.name}}</td> <td>{{tea.salary}}</td> <td>{{tea.address}}</td> </tr> </table> </p> </ul> </div> `, props:{}, data(){ return { userList:['fd','rr','tt'], tea:{}, } }, mounted(){ axios.all([this.getList(), this.getTea()]) .then(axios.spread(function (acct, perms) { console.log("all request finished"); console.log(acct); })); }, methods:{ getList(){ const self=this; axios.get('../data/a1.php') .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); }); }, //第二个请求 getTea(){ const self=this; axios.get('../data/a2.php',{ params:{id:2,} //name:'fafa' }).then(function(res){ self.tea =res.data[0]; }); } } }; const myVue = new Vue({ el:'#app', components:{ myF1:c1 }, }); </script>
我在php文件中作了一个延时处理。
a2.php
<?php $conn=mysqli_connect('127.0.0.1','root','','axiox',3307); $sql="SET NAMES UTF8"; mysqli_query($conn,$sql); // $body = @file_get_contents('php://input'); //$body=json_decode($body) ; //$id=$body->id; // $id=$_POST['id']; $id=$_GET['id']; $sql="SELECT * FROM tea WHERE id=$id"; $result=mysqli_query($conn,$sql); $list=mysqli_fetch_assoc($result); $arr=[]; $arr[]=$list; sleep(5); echo json_encode($arr); // print_r( json_encode($res)); ?>
a1.php
<?php // header("Content-Type:application/json;charset=UTF8"); // header("Content-Type:application/x-www-form-urlencoded;charset=UTF8"); $myDB= new PDO('mysql:host=127.0.0.1;dbname=axiox;port=3307','root',''); //$id=$_GET['id']; // $lname=$_POST['lastname']; //$body = @file_get_contents('php://input'); //$fname=$_POST['firstname']; //echo $body ; // echo $fname; if($myDB){ $res= $myDB->query("select * from stu"); while($row = $res->fetch( PDO::FETCH_ASSOC)){ // print_r($row); $arr[]=$row; } } else{ die("fali"); } sleep(5); print_r( json_encode($arr)); ?>
我本觉得在js里面axios.all的两个请求都执行问以后才执行 console.log("all request finished");
可是结果不是,而是先输出了这句话,,,,,毁三观
getList(){ const self=this; axios({ method:'get', url:'../data/a2.php', // responseType:'stream', params:{ id:2, } }) .then(function(res) { self.tea=res.data[0]; }); },
5)axios.create的使用,主要用于自定义请求配置。
详情看文档,,,,,
6)拦截器的使用(主要用于在请求等待时候作一些优化处理)
基本语法:
axios.interceptors.request.use(function (config) { // Do something before request is sent console.log("请求以前"); return config;//这句话不能丢 }, function (error) { // Do something with request error console.log("对错误deal"); return Promise.reject(error); })
demo:
建立一个组件
const c1={ template:` <div> <p>this is a demo </p> <table> <tr> <td>id</td> <td>name</td> <td>salary</td> <td>address</td> </tr> <tr> <td>{{tea.id}}</td> <td>{{tea.name}}</td> <td>{{tea.salary}}</td> <td>{{tea.address}}</td> </tr> </table> </div>`, props:{}, data(){ return { tea:{ id:1, name:'eee', salary:1233, address:'中国天安门' }, } }, methods:{ getList(){ const self=this; self.createInter(); axios.get('../data/a4.php',{///a4.php作了延时处理 params:{ id:2 } }).then(function(res){ self.tea=res.data[0]; },function(err){ console.log(err); }); }, createInter(){ const interOne=axios.interceptors.request.use(function (config) { // Do something before request is sent console.log("请求以前"); return config; }, function (error) { // Do something with request error console.log("对错误deal"); return Promise.reject(error); }) const interTwn= axios.interceptors.response.use(function (response) { // Do something with response data axios.interceptors.request.eject(interOne);//取消一个拦截器 console.log("this is after"); return response; }, function (error) { // Do something with response error return Promise.reject(error); }) } }, mounted(){ this.getList(); } }; const myVue=new Vue({ el:'#app', components:{ myF1:c1, } });
实际效果以下:(能够看到在必定的时间延迟以后会输出‘this is after’,而且也请求到了后端数据......)