项目需求:列表式切换商品,有时候上一次请求的结果非常慢,而我又点了另外一个商品,这时候第二次请求的接口比上一次快,那么就点击第二次的商品看到的信息却是上一次的商品信息,这样的用户体验极其不好;
解决方案:在点击下一个商品的时候,将上一个商品请求的接口中断取消请求。
axios官网给出了取消请求的方法:

方法一:
axios.get('/user/12345', {
  cancelToken: axios.CancelToken.source().token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: axios.CancelToken.source().token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
方法二:
let cancel;
axios.get('/user/12345', {
  cancelToken: new axios.CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

根据项目需求给出解决方案:

vue:
data(){
    return{
        source: null, //存放取消的请求方法
    }
},
methods:{
    cancelQuest(){
        if(typeof this.source ==='function'){
            this.source('终止请求'); //取消请求
        }
    },
    getInfo(id){
        const _this = this;
        this.cancelQuest(); //在请求发出前取消上一次未完成的请求;
        //发送请求
        this.axios.get(`/markets/tradeInfo/${id}?top=40`,{
            cancelToken: new this.axios.CancelToken(function executor(c) {
            _this.source = c;
          })
        }).then(res =>{
            //handle result
        }).catch(error => {
            if (this.axios.isCancel(err)) {
                console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
            } else {
                //handle error
                console.log(err);
            }
        })
    }
}

在经过这么处理后,用户点击快时,看到的商品信息就是最后点击的商品的了;如有需要,可以自行封装在axios的业务方法里面。

Logo

前往低代码交流专区

更多推荐