为了少写一行代码,而多写几十行代码?按钮loading的优化
2020-07-10 本文已影响0人
Lawrence_4aee
背景
最近的新需求,UI设计了在原本项目中没有用到的交互形式,在按钮中loading

一般对于这种封装,都可能会和elementUI等主流的控制方式相同,即加一个loading的属性,true则loading显示,false则loading隐藏;但是这种做法其实非常愚蠢且笨重
以Vue为例,你需要在你的业务代码的data中,注册一个和业务无关的loading用于控制按钮的加载中状态,还需要在每次点击和点击结束之后控制按钮的true、false;如果你的按钮需要执行的事情多一些,那么你就要多写很多this.loading = true、this.loading = false
本着“为了以后少写一行代码,现在可以多写一堆代码”的原则,这种组件糟糕的使用体验是我不能忍受的
优化
一般来说,按钮loading都是耗时的异步操作,那我们只需要在点击的时候,回调一个promise,当promise被处理的时候,就可以关闭loading了;当然,为了考虑到可能的用属性控制loading的场景,这个老旧的功能也是要实现的。
看代码
btn-loading组件
<template>
<rich-button
:primary="true"
class="gradient"
:disabled="btnDisabled"
@click="onclick"
><Loading v-show="loading || onloading" /><span>{{
btnText
}}</span></rich-button
>
</template>
<script>
import Loading from './d-loading/index';
export default {
name: 'LoadingBtn',
components: {
Loading,
},
props: {
loading: {
type: Boolean,
default: false,
},
btnText: {
type: String,
default: String,
},
disabled: {
type: Boolean,
default: false,
},
},
computed: {
btnDisabled() {
return this.loading || this.onloading || this.disabled;
},
},
data() {
return {
onloading: false,
};
},
methods: {
onclick() {
this.onloading = true;
this.$emit('click', (promise) => {
promise
.then(() => {
this.onloading = false;
})
.catch((e) => {
this.onloading = false;
});
});
},
},
};
</script>
组件使用
只需给回调函数传入耗时操作的promise即可,告别加loading和到处写this.loading

