使用vue编写应该父子组件的Spin 加载案例,点击子组件按钮开始,跑完子组件里面的接口然后恢复原来的状态
时间: 2023-08-18 16:20:55 浏览: 37
好的,下面是一个使用 Vue 编写的父子组件 Spin 加载案例,点击子组件按钮开始,跑完子组件里面的接口然后恢复原来的状态:
父组件代码:
```html
<template>
<div>
<ChildComponent @loading="handleLoading"></ChildComponent>
<Spin :show="loading"></Spin>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
import Spin from './Spin.vue'
export default {
components: {
ChildComponent,
Spin
},
data() {
return {
loading: false
}
},
methods: {
handleLoading(loading) {
this.loading = loading
}
}
}
</script>
```
子组件代码:
```html
<template>
<div>
<button @click="handleClick">开始</button>
</div>
</template>
<script>
export default {
data() {
return {
loading: false
}
},
methods: {
handleClick() {
this.loading = true
// 模拟接口请求
setTimeout(() => {
this.loading = false
this.$emit('loading', false)
}, 2000)
}
}
}
</script>
```
Spin 组件代码:
```html
<template>
<div v-show="show" class="spin">
<div class="spin-box"></div>
</div>
</template>
<style>
.spin {
position: fixed;
z-index: 999;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.spin-box {
width: 40px;
height: 40px;
border-radius: 50%;
border: 4px solid #fff;
border-top-color: #1890ff;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
<script>
export default {
props: {
show: {
type: Boolean,
default: false
}
}
}
</script>
```
在父组件中,我们通过 `loading` 变量来控制 Spin 组件的显示和隐藏,当子组件中的按钮被点击时,我们通过 `$emit` 向父组件发送 `loading` 事件,来控制 Spin 组件的显示和隐藏。
具体实现时,我们在子组件中模拟接口请求,请求结束后通过 `$emit` 向父组件发送 `loading` 事件,将 `loading` 变量设为 `false`,从而隐藏 Spin 组件。