Vue插件——vue-resource

一、vue-resource

插件下载:https://github.com/pagekit/vue-resource

vue-resource是Vue的插件,通过XMLHttpRequest或JSONP发起请求或处理响应。

  <script src="lib/vue.js"></script> <!-- 先引入vue的包 -->
  <script src="lib/vue-resource.js"></script>

1、HTTP请求/响应

https://github.com/pagekit/vue-resource/blob/develop/docs/http.md

在Vue对象上挂载$http属性来提供http服务,在全局使用Vue.http,在一个Vue实例中使用this.$http。

通过response.body拿到服务器返回的数据。

手动发起的post请求,默认没有表单格式,有的服务器处理不了。通过post方法的第三个参数{ emulateJSON: true }设置提交的内容类型为普通表单数据格式application/x-wwww-form-urlencoded。

this.$http.get('/someUrl', [config]).then(successCallback, [errorCallback]);
this.$http.post('/someUrl', [body], [config]).then(successCallback, [errorCallback]);
this.$http.jsonp('/someUrl', [config]).then(successCallback, [errorCallback]);
{
  this.$http.get('/someUrl').then(response => {
    // success callback
    // console.log(response.body);
  }, response => {
    // error callback
  });
}

2、配置

https://github.com/pagekit/vue-resource/blob/develop/docs/config.md

配置根路径和  的默认值。如果配置了根域名,则发送请求时的相对路径前面不能带'/',否则不能与根路径作拼接。

// 全局
Vue.http.options.root = '/root';
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';

// 在Vue实例局部
new Vue({
  http: {
    root: '/root',
    headers: {
      Authorization: 'Basic YXBpOnBhc3N3b3Jk'
    }
  }
})

全局设置emulateJSON:true

Vue.http.options.emulateJSON = true;

二、vue-axios

 

vue-preview

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章