在vue中axios设置timeout超时的操作

 更新时间:2020年09月04日 09:32:59   作者:七侠剑客  
这篇文章主要介绍了在vue中axios设置timeout超时的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在做vue项目的时候,由于数据量查询比较大,所以前台调用接口数据的时候,往往要等很久,所以需要设置个超时,当超过设置时间就让向页面返回一个状态,让使用者不用一直等。

通过官网api查询,对其超时讲解不是很多,但其和Jquery中请求非常类似

Jquery请求方式

$.ajax({
 url: '接口地址',
 type:'get', //请求方式get或post
 data:{}, //请求所传的参数
 dataType: 'json', //返回的数据格式
 timeout: 4000, //设置时间超时,单位毫秒
 success: function(result) {
 console.log('OK')
 },
 error: console.log('error')
 })

vue中请求方式:

axios.post( //请求方式
url, //接口地址
params, //传递参数
{timeout: 1000 * 60 * 2}) //设置超时,单位毫秒
.then(function(res){
 console.log(res);
}).catch((error) => {
 console.log('error')
})

所以可以再请求中通过timeout设置请求超时

补充知识:vue中用axios请求接口,处理网络失败和网络超时问题,axios拦截器

前端经常要对服务器的错误信息做处理,小编是头一次做,就遇到了很多问题

首先,是封装的请求数据的方法

import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';
import wx from 'weixin-js-sdk';
import {
 Toast
} from 'mint-ui';

axios.defaults.timeout = 10000;
// 拦截
axios.interceptors.request.use(function (config) {
 return config
}, function (error) {
 return Promise.reject(error);
})
axios.interceptors.response.use(
 response => {
 if (typeof(response) != 'String'&&response.data.errno !== 0 && response.config.url.indexOf('searchorderoyidornumber') < 0 && response.config.url.indexOf('upload') < 0) {
  response.data['data'] = response.data['data'] || {};
  Toast(response.data.errmsg)
 }
 if (typeof(response) != 'String'&&response.data.errno == 3521) {
  localStorage.clear();
  location.href = '#/login'
 }
 return response.status == 200 ? response.data : response;
 // return response
 },
 error => {
 //String(error).toLowerCase().indexOf('timeout')
 if (error && error.stack.indexOf('timeout') > -1) {
  Toast('请求超时')
 }
 // let config = error.config;
 // if (!config || !config.retry) return Promise.reject(err);
 // config.__retryCount = config.__retryCount || 0;

 // // Check if we've maxed out the total number of retries
 // if (config.__retryCount >= config.retry) {
 // // Reject with the error
 // return Promise.reject(err);
 // }

 // // Increase the retry count
 // config.__retryCount += 1;

 // // Create new promise to handle exponential backoff
 // var backoff = new Promise(function (resolve) {
 // setTimeout(function () {
 //  resolve();
 // }, config.retryDelay || 1);
 // });

 // // Return the promise in which recalls axios to retry the request
 // return backoff.then(function () {
 // return axios(config);
 // });
 }
);
let axios_post = function (url, params) {
 return new Promise((resolve, reject) => {
 if (!localStorage.getItem('token') || localStorage.getItem('token') == '') {
  axios.get('/gettoken').then((res) => {
  localStorage.setItem('token', res.data.token)
  axios.post(url, qs.stringify(params),
  {
   headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
   }
  }).then(res => {
   resolve(res)
  }).catch(err => {
   reject(err)
  })
  }).catch(err => {
  reject(err)
  })
 } else {
  params = url.indexOf('login') > -1 ? {
  ...params,
  _token: localStorage.getItem('token')
  } : {
  ...params,
  _token: localStorage.getItem('token'),
  S: localStorage.getItem('S'),
  U: localStorage.getItem('U')
  }
  let options = {};
  options['maxContentLength'] = 1024000000;
  if(url.indexOf('uplpoad') > -1){
  options['timeout'] = 1000 * 30;
  }
  axios.post(url, params, options).then(res => {
  resolve(res)
  }).catch(err => {
  reject(err)
  })
 }
 })
}
let axios_get = function (url, params) {
 let _params = typeof (params) == 'object' ? params : {}
 _params = {
 ..._params,
 S: localStorage.getItem('S'),
 U: localStorage.getItem('U')
 }
 return new Promise((resolve, reject) => {
 axios.get(url, {
  'params': _params
 }).then(res => {
  if (res.errno !== 0) {
  reject(res)
  }
  resolve(res)
 }).catch(err => {
  reject(err)
 })
 })
}
let getCookie = function(cookieName) {
 var cookieValue = "";
 if (document.cookie && document.cookie != '') {
  var cookies = decodeURIComponent(document.cookie).split(';');
  for (var i = 0; i < cookies.length; i++) {
   var cookie = cookies[i].trim();
   // if (cookie.substring(0, cookieName.length + 1).trim() == cookieName.trim() + "=") {
   //  cookieValue = cookie.substring(cookieName.length + 1, cookie.length);
   //  break;
   // }
   var cookie = cookies[i].trim();
   var cookieArr = cookie.split('=');
   if(cookieArr[0] == cookieName.trim()){
    cookieValue = cookieArr[1];
    break;
   }
  }
 }
 return cookieValue;
}

let setCookie = function(name,value){ 
 var Days = 30; 
 var exp = new Date(); 
 exp.setTime(exp.getTime() + Days*24*60*60*1000); 
 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 

Vue.prototype.$http = axios;
Vue.prototype.$get = axios_get;
Vue.prototype.$post = axios_post;
Vue.prototype.$getCookie = getCookie;
Vue.prototype.$setCookie = setCookie;

在组件中直接this.$post()这样用即可。

以上这篇在vue中axios设置timeout超时的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • vue-cli4.0多环境配置变量与模式详解

    vue-cli4.0多环境配置变量与模式详解

    这篇文章主要介绍了vue-cli4.0多环境配置变量与模式详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Vue中使用计算属性的知识点总结

    Vue中使用计算属性的知识点总结

    在本篇文章里小编给大家整理了一篇关于Vue中使用计算属性的知识点总结内容,对此有兴趣的朋友们可以跟着学习参考下。
    2021-12-12
  • Vue中的变量赋值问题

    Vue中的变量赋值问题

    这篇文章主要介绍了Vue中的变量赋值问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • vue 弹框产生的滚动穿透问题的解决

    vue 弹框产生的滚动穿透问题的解决

    这篇文章主要介绍了vue 弹框产生的滚动穿透问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • Vue中UI组件库之Vuex与虚拟服务器初识

    Vue中UI组件库之Vuex与虚拟服务器初识

    这篇文章主要介绍了Vue中UI组件库之Vuex与虚拟服务器初识,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-05-05
  • vue动态绑定v-model属性名方式

    vue动态绑定v-model属性名方式

    这篇文章主要介绍了vue动态绑定v-model属性名方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • 关于axios配置多个请求地址(打包后可通过配置文件修改)

    关于axios配置多个请求地址(打包后可通过配置文件修改)

    这篇文章主要介绍了关于axios配置多个请求地址(打包后可通过配置文件修改),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • Vue组件通信实践记录(推荐)

    Vue组件通信实践记录(推荐)

    本篇文章主要介绍了Vue组件通信实践记录(推荐),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • Vue源码解析之数组变异的实现

    Vue源码解析之数组变异的实现

    这篇文章主要介绍了Vue源码解析之数组变异的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-12-12
  • 基于Vue实现的多条件筛选功能的详解(类似京东和淘宝功能)

    基于Vue实现的多条件筛选功能的详解(类似京东和淘宝功能)

    这篇文章主要介绍了Vue多条件筛选功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05

最新评论