useModal对弹窗进行逻辑封装

useModal.js

import { nextTick, ref } from 'vue'
import { isFunction } from '@/utils/judge'

export function useModal() {
	// 标题
	// 执行ok、cancel方法
	const visible = ref(false)
	const loading = ref(false)

	const hideModal = () => {
		visible.value = false
	}

	const showModal = () => {
		visible.value = true
	}

	const toggleLoading = () => {
		loading.value = !loading.value
	}
	const handleOk = async (callbackFn) => {
		if (!callbackFn || !isFunction(callbackFn)) return
		toggleLoading()
		console.log('output-> 1', 1)
		callbackFn(() => {
			console.log('output-> 2', 2)
			toggleLoading();
			hideModal();
		})
	}

	return {
		visible,
		showModal,
		hideModal,
		handleOk,
		loading,
		toggleLoading
	}
}

使用案例

<template>
	<div>
		<a-button type="link" @click="showModal">详情</a-button>
		<a-modal v-model:visible="visible"
						 title="登录表单"
		>
			<a-form
				ref="formRef"
			>
				<a-form-item name="name">
					<a-input
						v-model:value="state.userName"
						autocomplete="off"
						placeholder="请输入账号"
					>
						<template v-slot:prefix>
							<UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
						</template>
					</a-input>
				</a-form-item>
			</a-form>
			<template #footer>
				<a-button key="back" @click="hideModal">取消</a-button>
				<a-button key="submit"
									type="primary" :loading="loading"
									@click="handleOk(submitFn)">提交</a-button>
			</template>
		</a-modal>
	</div>
</template>
<script setup>
import { useModal } from '@/hooks/useModal'
import { message } from 'ant-design-vue'
import { UserOutlined } from '@ant-design/icons-vue'
import { reactive } from 'vue'

let {visible, loading, handleOk, hideModal, showModal} = useModal();

const state = reactive({
	userName: ''
})
const submitFn = async (callback) => {
	setTimeout(() => {
		// 提交逻辑代码
		console.log('output-> state.userName::: ', state.userName)
		message.warn('提交成功')
		callback()
	}, 2000)
	return true;
}


</script>


posted @ 2024-02-29 18:19  Felix_Openmind  阅读(149)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}