vue学习(二)vue-resource全攻略(二)

实例补充

post请求

实例一:简单的post提交

// POST /someUrl
  this.$http.post('/someUrl', {foo: 'bar'}).then(response => {
    // get status
    response.status;
    // get status text
    response.statusText;
    // get 'Expires' header
    response.headers.get('Expires');
    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });

实例二:带有配置项的post提交

export default({
    name:'home',
    mounted:function () {
      this.$http.post('http://api.chairis.cn/api?app_id=123456&method=demo.run',{
          body: {
            name: {
              first_name: 'chain',
              last_name: 'zhang'
            },
            email: 'zzceng@126.com'
          }
      },{emulateJSON: true}).then(response => {
          console.log('请求成功')
      },
      response => {
          console.log('请求失败')
      });
    }
  })

在这里我们看到了陌生的东西emulateJSON, 为什么要加这个参数呢,想知道为什么,那么就把他去掉试试,去掉了,你会发现请求失败了,报以下错误:

这是个跨域请求,没有权限的问题,但是已加上这个属性就可以了。

get请求

实例一:不带参数的get提交

var demo = new Vue({
    el: '#app',
    data: {
        gridColumns: ['customerId', 'companyName', 'contactName', 'phone'],
        gridData: [],
        apiUrl: 'http://211.149.193.19:8080/api/customers'
    },
    ready: function() {
        this.getCustomers()
    },
    methods: {
        getCustomers: function() {
            this.$http.get(this.apiUrl)
                .then((response) => {
                    this.$set('gridData', response.data)
                })
                .catch(function(response) {
                    console.log(response)
                })
        }
    }
})

实例二:带查询参数和自定义请求头的GET请求

// GET /someUrl?foo=bar
  this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '...'}}).then(response => {
    // success callback
  }, response => {
    // error callback
  });

实例三:获取图片并使用blob()方法从响应中提取图片的主体内容。

// GET /image.jpg
  this.$http.get('/image.jpg', {responseType: 'blob'}).then(response => {
    // resolve to Blob
    return response.blob();
  }).then(blob => {
    // use image Blob
  });

jsonp请求(可以获取本域之外的一些数据)

实例一:不带参数

getCustomers: function() {
    this.$http.jsonp(this.apiUrl).then(function(response){
        this.$set('gridData', response.data)
    })
}

实例二:带参数

this.$http.jsonp("https://sug.so.360.cn/suggest",{
        word:"a" 
}).then(function(res){ 
        alert(res.data.s);
},function(res){
        alert(res.status);
});
原文地址:https://www.cnblogs.com/kunmomo/p/12448286.html