vue学习之ajax请求

vue本身不支持发送AJAX请求,需要使用vue-resource(vue1.0版本)、axios(vue2.0版本)等插件实现。

axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。

resource请求

import VueResource from 'vue-resource'
Vue.use(VueResource)
this.$http.get("")
或者
Vue.http.get/post

axios请求

参考:GitHub上axios,查看API文档

安装axios并引入

1)npm的方式: $ npm install axios  -S
2)bower的方式:$ bower install axios
3)cdn的方式:<script src=”https://unpkg.com/axios/dist/axios.min.js”></script>
import axios from 'axios'

get请求:

// GET request for remote image
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

具体的请求配置项,查看文档:https://github.com/axios/axios#request-config

响应数据

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

interceptors拦截器

拦截器应用场景总结

发起请求加载loading请求结束关闭loading

拦截request:

设置全局请求为ajax请求

有token值则配置上token值

拦截response:

做一些错误处理

跨域请求

使用vue-resource发送跨域请求:vue实战——vue中发送AJAX请求

  methods:{
     sendJsonp:function(){
       this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
               { params:{ wd:
'a' }, jsonp:'cb' }).then(function(res){ console.log(res.data); }); } }

在store.js中封装http请求的方法

推文:vue中http请求

参考文章:

vue实战——vue中发送AJAX请求

Vue.js-几种请求方式

vue-axios interceptors(拦截器)实际应用

axios拦截设置和错误处理

Vue+axios(interceptors) 实现http拦截 + router路由拦截 (双拦截)+ 请求自带loading效果

猜你喜欢

转载自www.cnblogs.com/yaoyao-sun/p/10362668.html