这是我自己写的一命令式组件,分享给大家
在前端开发中,命令式编程为我们提供了一种更加直观和灵活的方式来操作 UI 和管理状态。今天,我想与大家分享一款我自己写的命令式组件,它能够帮助开发者更高效地进行状态管理和 UI 渲染。
import type { App } from 'vue';
import Loading from '@/components/Loading/Loading.vue';
import { createApp, h } from 'vue';
let loadingApp: App | null = null; // 用于保存 Vue 实例
let containerBox: HTMLElement | null = null; // 用于保存加载容器
export function showLoading(): void {
// 条件编译:只在 H5 平台使用 Vue 动态创建 loading
// #ifdef H5
// 创建一个容器
if (loadingApp)
return;
containerBox = document.createElement('div');
containerBox.style.position = 'fixed'; // 确保 loading 在视口内
containerBox.style.top = '0';
containerBox.style.left = '0';
containerBox.style.width = '100%';
containerBox.style.height = '100%';
containerBox.style.zIndex = '9999'; // 确保 loading 在最上层
document.body.appendChild(containerBox);
// 使用 createApp 动态创建并挂载 YyLoading 组件
loadingApp = createApp({
render() {
return h(YyLoading); // 挂载 YyLoading 组件
},
});
// 将 loadingApp 挂载到 body 中的 containerBox
loadingApp.mount(containerBox);
// #endif
// 条件编译:只在 MP-WEIXIN 平台使用 uni.showLoading
// #ifndef MP-WEIXIN
uni.showLoading({
title: '加载中...',
mask: true, // 显示遮罩层
});
// #endif
}
export function closeLoading(): void {
// 条件编译:只在 H5 或 MP-WEIXIN 平台卸载 Vue 组件
// #ifdef H5
if (!loadingApp || !containerBox)
return;
// 卸载组件
loadingApp.unmount(); // 卸载组件
containerBox.remove(); // 移除容器
loadingApp = null; // 清理 Vue 实例引用
containerBox = null; // 清理容器引用
// #endif
// 条件编译:只在 MP-WEIXIN 平台使用 uni.hideLoading
// #ifdef MP-WEIXIN
uni.hideLoading();
// #endif
}
这个组件的设计理念是简化复杂的界面交互,使得开发者能够通过简单的 API 调用来控制组件的状态和视图渲染。它不依赖于复杂的声明式状态管理,而是通过直接的命令和控制,实现更灵活和即时的操作。开发者只需要调用相应的命令,组件就能自动根据命令调整 UI 的状态,极大地减少了代码的冗余和复杂度。
通过这个命令式组件,大家可以更加专注于业务逻辑,而不用频繁地手动操作 DOM 或进行多余的状态传递。无论是处理复杂的用户交互,还是简化组件的可重用性,这个组件都能为你的项目带来更多的便捷和灵活性。
希望我的分享能对你们的开发工作有所帮助,欢迎大家试用并提出宝贵的意见和建议!