axios

vue2.0 推荐使用axios

  1. npm install axios
  1. //调用
  2. const baseUrl = "https://www.fastmock.site/mock/ad533d42207a36676b39a3d5cd8dfe5f/api";
  3. axios.get(`${baseUrl}/backlist`)
  4. .then((res)=>{
  5. this.tableData = res.data.tabledata //获取接口的表格数据
  6. this.oldTable = res.data.tabledata
  7. this.$emit('Datatotal',this.tableData.length)//将导航栏总数设置为表格数据总数
  8. })
  9. .catch(error =>{
  10. console.log(error)
  11. })

执行多个并发请求

  1. getUser(){
  2. return axios.get('/user')
  3. }
  4. getUsePermissions(){
  5. return axios.get('/user/xx/xx')
  6. }
  7. axios.all([getUser(),getUsePermissions()])
  8. .then(axios.spread(functiong(acct,perms){
  9. }))

axios API

  1. axios({
  2. method:'post',
  3. url:'user/xx',
  4. data:{
  5. firstName:'111',
  6. lastName:'222'
  7. }
  8. });
  9. axios({
  10. method:'get',
  11. url:'user/xx',
  12. })
  13. .then(res=>{
  14. })

vue-resource

GET

  1. window.onload = function(){
  2. var vm = new Vue({
  3. el:'#box',
  4. data:{
  5. msg:'Hello World!',
  6. },
  7. methods:{
  8. get:function(){
  9. //发送get请求
  10. this.$http.get('/ajax').then(function(res){
  11. document.write(res.body);
  12. },function(){
  13. console.log('请求失败处理');
  14. });
  15. }
  16. }
  17. });
  18. }

使用get 传递数据的时候 可以使用两个参数,后面那个参数是传给后端的

  1. this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){
  2. document.write(res.body);
  3. },function(res){
  4. console.log(res.status);
  5. });

POST
post 发送数据到后端,需要第三个参数 {emulateJSON:true}。
emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

  1. this.$http.post('/ajax',{name:"xxx",url:"xxxxx"},{emulateJSON:true}).then(function(res){
  2. document.write(res.body);
  3. },function(res){
  4. console.log(res.status);
  5. });