vue处理axios多次请求数据显示
场景:
一个搜索框,要求用户输入内容改变之后立即进行搜索
遇到的问题:
用户频繁的进行搜索词修改,会触发很多次搜索请求,如果请求有延时,就会出现显示不正确的现象
比如下面这个例子:
- 请求1发出后,存在延时大,响应1后返回;
- 请求2发出后,延时小,响应2先返回;
- 最后显示的内容是响应1;
而我期待的显示内容,是最后一次的请求结果响应2
请求1 -------> 延时 ---------> 响应1
请求2 -> 延时 -> 响应2
服务端代码
server.py
# -*- coding: utf-8 -*-
from flask import flask, request
from flask_cors import cors
import time
import random
app = flask(__name__)
# 允许跨域
cors(app, supports_credentials=true)
# 路由
@app.route('/search')
def search():
# 模拟网络延时
sleep = random.random() * 2
time.sleep(sleep)
keyword = request.args.get('keyword')
return {'keyword': keyword, "sleep": sleep}
if __name__ == '__main__':
app.run(debug=true)
客户端代码
1、直接请求,会出现数据显示不对的情况
<template>
<div class="">
<input
type="text"
@input="handleinput"
>{{result}}</div>
</template>
<script>
import axios from 'axios';
export default {
name: '',
data() {
return {
result: '',
};
},
methods: {
async handleinput(e) {
const keyword = e.target.value;
const res = await this.search(keyword);
this.result = res.data;
},
// 直接搜索:可能显示的不是最后一次搜索结果
async search(keyword) {
return await axios.get('http://127.0.0.1:5000/search', {
params: { keyword: keyword },
});
},
},
};
</script>
<style lang="scss" scoped>
</style>2、增加一个定时器
import axios from 'axios';
export default {
name: '',
data() {
return {
result: '',
timer: null, // 定时器
};
},
methods: {
async handleinput(e) {
const keyword = e.target.value;
const res = await this.searchfortimeout(keyword);
this.result = res.data;
},
// 加定时器:会有一个延迟,如果有超过500ms的网络延时,也会出现数据不一致
async searchfortimeout(keyword) {
return new promise((resolve, reject) => {
// 清除没执行的timer定时器
cleartimeout(this.timer);
this.timer = settimeout(() => {
try {
const res = axios.get('http://127.0.0.1:5000/search', {
params: { keyword: keyword },
});
resolve(res);
} catch (e) {
reject(e);
}
}, 500);
});
},
}
};3、加请求时间戳
import axios from 'axios';
// 使用axios的拦截器
const instance = axios.create();
instance.interceptors.request.use(
(config) => {
config['x-timestamp'] = new date().gettime();
return config;
},
(err) => {
return promise.reject(err);
}
);
instance.interceptors.response.use(
(res) => {
res.data.timestamp = res.config['x-timestamp'];
return res;
},
(err) => {
return promise.reject(err);
}
);
export default {
name: '',
data() {
return {
result: '',
timestamp: 0, // 相当于版本号
};
},
methods: {
async handleinput(e) {
const keyword = e.target.value;
const res = await this.searchfortimestamp(keyword);
// 如果时间戳大于当前记录的时间戳则更新数据
if (res.data.timestamp > this.timestamp) {
this.timestamp = res.data.timestamp;
this.result = res.data;
}
},
// 加请求时间戳:类似乐观锁
async searchfortimestamp(keyword) {
return instance.get('http://127.0.0.1:5000/search', {
params: { keyword: keyword },
});
},
},
};vue axios多次请求一个接口取消前面请求
方法一
var canceltoken = axios.canceltoken;
var source = canceltoken.source(); // 每次调用接口之前都赋值一下 不然不会触发请求
axios.get('/user/12345', {//get请求在第二个参数
canceltoken: source.token
}).catch(function(thrown) {
});
axios.post('/user/12345', {//post请求在第三个参数
name: 'new name'
}, {
canceltoken: source.token
});
source.cancel('不想请求了');方法二
const canceltoken = axios.canceltoken;
let cancel;
axios.get('/user/12345', {
canceltoken: new canceltoken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
});
// cancel the request
cancel();总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论