uniapp开发4--实现耗时操作的加载动画效果
下面是使用 Vue 组件的方式,在 uni-app 中封装耗时操作的加载动画效果及全屏遮罩层的组件的示例。
组件结构:
components/loading.vue
: 组件文件,包含 HTML 结构、样式和 JS 逻辑。
代码:
<template><view class="loading-overlay" v-if="visible"><view class="loading-content"><view class="spinner"></view><text class="loading-text">{{ text }}</text></view></view>
</template><script>
export default {name: 'Loading',props: {visible: {type: Boolean,default: false},text: {type: String,default: '加载中...'}},data () {return {}},methods: {close () {this.$emit('update:visible', false) // 用于双向绑定 visible}}
}
</script><style scoped>
.loading-overlay {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色遮罩 */z-index: 9999;display: flex;align-items: center;justify-content: center;
}.loading-content {display: flex;flex-direction: column;align-items: center;background-color: #fff;padding: 20px;border-radius: 8px;box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}.spinner {width: 40px;height: 40px;border: 5px solid #f3f3f3;border-top: 5px solid #3498db;border-radius: 50%;animation: spin 0.8s linear infinite;margin-bottom: 10px;
}.loading-text {font-size: 14px;color: #666;
}@keyframes spin {0% {transform: rotate(0deg);}100% {transform: rotate(360deg);}
}
</style>
使用组件:
- 在页面中引入组件:
<template><view><button @click="startLoading">开始加载</button><!-- 引入并使用 loading 组件 --><loading :visible.sync="isLoading" text="正在登录..."></loading></view>
</template><script>
import Loading from '@/components/loading.vue'export default {components: {Loading},data () {return {isLoading: false, // 控制 loading 组件是否显示}},methods: {startLoading () {this.isLoading = true;// 模拟登录或请求setTimeout(() => {this.isLoading = false; // 停止加载}, 3000); // 3 秒后停止},}
}
</script>
要点解释:
visible
Prop: 控制组件的显示/隐藏。父组件可以双向绑定这个 prop,以便在需要的时候手动关闭加载组件。(使用了.sync
修饰符,需要发出update:visible
事件)text
Prop: 允许传递自定义的加载文字。loading-overlay
: 全屏遮罩层,设置了position: fixed
和较高的z-index
,盖住页面所有内容。背景颜色使用了半透明 (rgba
),让背景透出一点。spinner
: 转圈的 CSS 动画。close()
方法: 组件内部可以通过调用此方法来关闭自身,并通过emit
触发update:visible
事件。- 使用双向绑定: 使用
:visible.sync="isLoading"
可以让父组件的isLoading
和子组件的visible
双向绑定。 意味着父组件可以控制子组件的显隐,同时子组件也可以将自己的显隐状态同步给父组件。
如何使用:
- 将上面的组件文件保存到
components
目录中。 - 在需要使用加载组件的页面或组件中,先
import
导入,然后在components
选项中注册。 - 在模板中使用组件
优势:
- 封装性: 将加载逻辑和 UI 封装在一个组件中,方便复用。
- 可定制: 通过 props 可以灵活地控制组件的显示状态和文字内容。
- 样式隔离:
scoped
属性可以让组件的样式只作用于组件内部,避免污染全局样式。 - 易于控制 通过
isLoading
控制显隐
注意事项:
components
目录的路径可能需要根据你的项目结构进行调整。- 可以根据实际需要修改加载动画的样式。
- 如果需要更复杂的动画效果,可以考虑使用第三方动画库。
这种方式实现了一个可复用且易于控制的加载组件,在 uni-app 项目中非常实用。