Appearance
Ajax防止重复请求
增加loading
- 一般在数据请求的过程中,应该第一时间把页面loading住,等到数据请求完毕之后,再关闭loading。
vue
<template>
<!-- 保存 -->
<el-button size="small" @click="onSave">保存</el-button>
</template>
<script>
export default {
data() {
return {
form: {}, //表单数据
}
},
methods: {
/**
* 保存数据
*/
save() {
return new Promise((resolve, reject) => {
fetch.post('xxxxx', this.form).then(resolve).catch(reject);
});
},
/**
* 处理保存
*/
async onSave() {
try {
this.$loading();
await this.save();
} catch (err) {
console.error(err);
this.$message({
type: 'error',
message: err.msg,
});
} finally {
this.$loadingClose();
}
}
}
};
</script>
事件增加防抖
- 对于一些关键性的业务,例如支付,除了增加loading之外,还应该对按钮点击事件做防抖处理(防抖函数必须增加示例代码中的配置),防止重复提交。
vue
<template>
<!-- 支付 -->
<el-button size="small" @click="debounceOnPay">支付</el-button>
</template>
<script>
export default {
data() {
return {
form: {}, //表单数据
}
},
created() {
this.debounceOnPay = _.debounce(this.onPay, 2000, {
leading: true,
trailing: false,
});
},
methods: {
/**
* 支付
*/
pay() {
return new Promise((resolve, reject) => {
fetch.post('xxxxx', this.form).then(resolve).catch(reject);
});
},
/**
* 处理支付
*/
async onPay() {
try {
this.$loading();
await this.pay();
} catch (err) {
console.error(err);
this.$message({
type: 'error',
message: err.msg,
});
} finally {
this.$loadingClose();
}
}
},
beforeDestroy() {
this.debounceOnPay.cancel();
}
};
</script>