本文已参与「新人创作礼」活动,一起开启掘金创作之路。
在接口未返回时连续点击多个按钮 接口返回会出现,点击按钮2时返回按钮1的数据
模拟接口请求
getRand (min, max) {
return Math.round(Math.random() * (max - min) + min)
},
mockInterface (data) {
// 模拟后端接口返回时间不确定,连续请求会出现最终显示数据与当前点击按钮的显示不一致
return new Promise(resolve => {
setTimeout(() => {
resolve('参数' + data)
}, this.getRand(0, 2000))
})
},
解决方案
handleClick (param) {
this.currentParam = param
this.mockInterface(param).then(res => {
console.log('p', param, this.currentParam)
// 解决方案
param === this.currentParam && console.log('re', res)
})
}
完整代码
<template>
<div>
<!-- 模拟table多气泡框请求 -->
<el-button type="primary" @click="handleClick(1)">按钮1</el-button>
<el-button type="primary" @click="handleClick(2)">按钮2</el-button>
</div>
</template>
<script>
export default {
data () {
return {
currentParam: ''
}
},
methods: {
getRand (min, max) {
return Math.round(Math.random() * (max - min) + min)
},
mockInterface (data) {
// 模拟后端接口返回时间不确定,连续请求会出现最终显示数据与当前点击按钮的显示不一致
return new Promise(resolve => {
setTimeout(() => {
resolve('参数' + data)
}, this.getRand(0, 2000))
})
},
handleClick (param) {
this.currentParam = param
this.mockInterface(param).then(res => {
console.log('p', param, this.currentParam)
// 解决方案
param === this.currentParam && console.log('re', res)
})
}
}
}
</script>
<style>
</style>