vue spin组件
时间: 2023-07-01 13:09:41 浏览: 211
Vue Spin 组件可以帮助我们在页面加载、数据加载等场景下,显示一个加载中的动画效果,以提升用户体验。
以下是一个简单的 Vue Spin 组件的示例代码:
```vue
<template>
<div class="spin" v-if="loading">
<div class="spinner"></div>
<div class="text">{{ text }}</div>
</div>
</template>
<script>
export default {
props: {
loading: {
type: Boolean,
default: false
},
text: {
type: String,
default: 'Loading...'
}
}
}
</script>
<style>
.spin {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.3);
z-index: 9999;
}
.spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 0.8s linear infinite;
margin-right: 8px;
}
.text {
color: #fff;
font-size: 16px;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
```
在上述代码中,我们定义了一个 `spin` 组件,包含两个 props:`loading` 和 `text`,分别用来控制组件是否显示和显示的文本内容。当 `loading` 为 `true` 时,组件会显示一个半透明的背景和一个旋转的动画,同时显示传入的文本内容。在样式中,我们使用了 flex 布局和 CSS 动画来实现动画效果。
使用时,只需要在父组件中引入 `spin` 组件,并传入相应的 props 即可:
```vue
<template>
<div>
<spin :loading="loading" :text="text"></spin>
<!-- 其他内容 -->
</div>
</template>
<script>
import Spin from './Spin.vue'
export default {
components: {
Spin
},
data() {
return {
loading: false,
text: 'Loading...'
}
},
methods: {
loadData() {
this.loading = true
// 模拟异步请求
setTimeout(() => {
this.loading = false
}, 2000)
}
}
}
</script>
```
在上述代码中,我们将 `spin` 组件引入到父组件中,并通过 `loading` 和 `text` props 控制组件是否显示和显示的文本内容。在 `loadData` 方法中,我们模拟了一个异步请求,并在请求开始前将 `loading` 设置为 `true`,请求结束后将其设置为 `false`。这样,在请求过程中,`spin` 组件就会自动显示和隐藏。