在应用创建的过程中,可能在不同的页面会遇到不同的 modal,如何整理这种类似的需求,我们可以对通用的逻辑进行抽离,用 key 值来界定不同的modal。对不同页面上的 modal 进行控制的时候,我们可以传入不同的参数来达到分别控制的效果。

    1. import { readonly, ref } from 'vue';
    2. export interface IModal {
    3. name: string;
    4. visible: boolean;
    5. }
    6. // 全局单例,放到最外层
    7. const modals = ref<IModal[]>([]);
    8. export default function useModal() {
    9. const registerModal = (name: string) => {
    10. modals.value.push({
    11. name,
    12. visible: false,
    13. } as IModal);
    14. };
    15. const findModal = (name: string): IModal | undefined => modals.value.find((m) => m.name === name);
    16. const isModalVisible = (name: string) => {
    17. const m = findModal(name);
    18. return m ? m.visible : undefined;
    19. };
    20. const showModal = (name: string) => {
    21. const m = findModal(name);
    22. if (m) m.visible = true;
    23. };
    24. const hideModal = (name: string) => {
    25. const m = findModal(name);
    26. if (m) m.visible = false;
    27. };
    28. const toggleModal = (name: string) => {
    29. const m = findModal(name);
    30. if (m) m.visible = !m.visible;
    31. };
    32. return {
    33. modals: readonly(modals),
    34. registerModal,
    35. isModalVisible,
    36. showModal,
    37. hideModal,
    38. toggleModal,
    39. };
    40. }

    通过以上的 composable 函数封装,我们就可以在不同的页面调用 useModal 对该页面上的 modal 进行注册之后进行单独的控制。