vue-resource请求超时timeout设置

请求超时设置通过拦截器Vue.http.interceptors实现具体代码如下

main.js里在全局拦截器中添加请求超时的方法

方法1:超时之后会调用请求中的onTimeoutd方法,then方法不会执行


Vue.http.interceptors.push((request, next) => { let timeout; // 如果某个请求设置了_timeout,那么超过该时间,会终端该(abort)请求,并执行请求设置的钩子函数onTimeout方法,不会执行then方法。 if (request._timeout) { timeout = setTimeout(() => { if(request.onTimeout) { request.onTimeout(request); request.abort() } }, request._timeout); } next((response) => { clearTimeout(timeout);
    return response; }) })

页面中用到vue-resource请求的地方如下设置即可。

this.$http.get('url',{
            params:{.......},
       ...... _timeout:
3000, onTimeout: (request) => { alert("请求超时"); } }).then((response)=>{
}
);

 方法2:超时之后可以在then的第二个error方法中获取,私以为这个方法更好一些

main.js中设置如下

Vue.http.interceptors.push((request, next) => {
    let timeout;
    // 這裡改用 _timeout
    if (request._timeout) {
        timeout = setTimeout(() => {
        //自定义响应体 status:408,statustext:"请求超时",并返回给下下边的next next(request.respondWith(request.body, { status:
408, statusText: '请求超时' })); }, request._timeout); } next((response) => {
    console.log(response.status)//如果超时输出408
    return response; }) })

页面请求设置

this.$http.get(`repairs/${this.repairs_id}`,{
                params:{with:'room;user'},
                _timeout:100,//设置超时时间
            }).then((response)=>{
            },(err)=>{
                console.log(err.status);//如果超时,此处输出408
});
/** 
 *             ,%%%%%%%%, 
 *           ,%%/\%%%%/\%% 
 *          ,%%%\c "" J/%%% 
 * %.       %%%%/ o  o \%%% 
 * `%%.     %%%%    _  |%%% 
 *  `%%     `%%%%(__Y__)%%' 
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%' 
 *  \\    .'          | 
 *   \\  /       \  | | 
 *    \\/         ) | | 
 *     \         /_ | |__ 
 *     (___________))))))) 攻城湿 
 * 
 *        _       _ 
 * __   _(_)_   _(_) __ _ _ __ 
 * \ \ / / \ \ / / |/ _` |'_ \ 
 *  \ V /| |\ V /| | (_| | | | | 
 *   \_/ |_| \_/ |_|\__,_|_| |_| 
 */ 

参考文章  https://segmentfault.com/q/1010000005800495/a-1020000005802004

 

posted @ 2016-11-29 17:16  杜培东  阅读(22452)  评论(2编辑  收藏  举报