Vue 学习笔记之四Vue的Ajax请求

1159

4. Vue的Ajax请求

4.1 Vue-resource插件介绍

下载地址:

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

$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的API更为简洁。另外,vue-resource还提供了非常有用的inteceptor功能,使用inteceptor可以在请求前和请求后附加一些行为,比如使用inteceptor在ajax请求时显示loading界面。

vue-resource的特点:

1. 体积小

vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。

2. 支持主流的浏览器

和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。

3. 支持Promise API和URI Templates

Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。
URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。

4. 支持拦截器

拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。

4.1.1 Methods

  • get(url, [config])
  • head(url, [config])
  • delete(url, [config])
  • jsonp(url, [config])
  • post(url, [body], [config])
  • put(url, [body], [config])
  • patch(url, [body], [config])

4.1.2 Config

ParameterTypeDescription
urlstringURL to which the request is sent
bodyObject, FormData, stringData to be sent as the request body
headersObjectHeaders object to be sent as HTTP request headers
paramsObjectParameters object to be sent as URL parameters
methodstringHTTP method (e.g. GET, POST, ...)
responseTypestringType of the response body (e.g. text, blob, json, ...)
timeoutnumberRequest timeout in milliseconds (0 means no timeout)
credentialsbooleanIndicates whether or not cross-site Access-Control requests should be made using credentials
emulateHTTPbooleanSend PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header
emulateJSONbooleanSend request body as application/x-www-form-urlencoded content type
beforefunction(request)Callback function to modify the request object before it is sent
uploadProgressfunction(event)Callback function to handle the ProgressEvent of uploads
downloadProgressfunction(event)Callback function to handle the ProgressEvent of downloads

4.1.3 Response

A request resolves to a response object with the following properties and methods:

PropertyTypeDescription
urlstringResponse URL origin
bodyObject, Blob, stringResponse body
headersHeaderResponse Headers object
okbooleanHTTP status code between 200 and 299
statusnumberHTTP status code of the response
statusTextstringHTTP status text of the response
MethodTypeDescription
text()PromiseResolves the body as string
json()PromiseResolves the body as parsed JSON object
blob()PromiseResolves the body as Blob object

4.1.4 实例

get请求

<!-- 导入vue.js和vue-resource.js,且按顺序导入 -->
<script src="../js/vue2.5.22.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/vue-resource1.5.1.js" type="text/javascript" charset="utf-8"></script>

<div id="app">
    {{ userList }}
    <button type="button" @click="getdata">get请求</button>
</div>

new Vue({
    el:'#app',
    data:{
        userList:null
    },
    methods:{
        getdata:function(){
            //请求的url
            var url = 'https://www.layui.com/demo/table/user/';
            //利用vue-resource发出Ajax请求
            this.$http.get(url)//发出请求
                .then(function(response){//获取服务器返回的数据
                this.userList = response.body;//获取当前url响应回来的数据
            });
        }
    }
})

post请求

new Vue({
    el:'#app',
    methods:{
        postdata:function(){
            //请求的url
            var url = 'https://www.layui.com/demo/table/user/';
            //利用vue-resource发出Ajax请求
            //post有三个参数:post(url,传入服务器的请求报文体数据,{emulateJson:true})
            this.$http.post(url,{name:'张三'},{emulateJson:true})//发出post请求
                .then(function(response){//获取服务器返回的数据
                console.log(response.body);//获取当前url响应回来的数据
            });
        }
    }
})

jsonp请求

new Vue({
    el:'#app',
    methods:{
        jsonpdata:function(){
            //请求的url
            var url = 'https://www.layui.com/demo/table/user/';
            //利用vue-resource发出Ajax请求
            //url后不需要跟callback参数
            this.$http.jsonp(url)
                .then(function(response){//获取服务器返回的数据
                console.log(response.body);//获取当前url响应回来的数据
            });
        }
    }
})