- 前言
- 实现
- 使用
前言
用到了Element-ui的loading
和el-button
,在点击按钮后按钮立刻进入加载状态,等待执行完某个操作后才停止加载。
实现
由于该按钮主要用于http请求,故取名为http-button
;在组件里面设置一个方法用于停止加载状态,将其作为事件参数传递给父组件。
HttpButton.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <template> <el-button @click="handleClick" :type="type" :loading="loading"> <slot></slot> </el-button> </template>
<script> export default { data() { return { loading: false, }; }, props: { type: {}, }, methods: { stopLoading() { this.loading = false; }, handleClick() { this.loading = true; this.$emit("click", this.stopLoading); }, }, }; </script>
|
使用
这里示例了一个最复杂的情况,就是既要在父组件中给@click
传递参数,还要执行子组件传递来的关闭加载状态的按钮,因此需要使用事件对象$event
来接收参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <div class="home"> <http-button type="primary" @click="handleClick('参数', $event)"> 按钮 </http-button> </div> </template>
<script> import HttpButton from "../components/HttpButton.vue";
export default { components: { HttpButton }, methods: { handleClick(arg, done) { console.log(arg); setTimeout(() => { done(); }, 3000); }, }, }; </script>
|
如果不需要在父组件中自定义参数,只需要写为:
1 2 3 4 5
| methods: { handleClick(done) { done(); } }
|