42 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
			
		
		
	
	
			42 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
| import { ElMessage } from "element-plus";
 | |
| import { useTemplateRef } from "vue";
 | |
| 
 | |
| /**
 | |
|  * @returns {Object} 返回一个包含以下属性的对象:
 | |
|  *  - validate {Function} 触发表单验证的异步方法
 | |
|  *  - formRef {Ref} 表单引用对象(用于 Vue 模板绑定)
 | |
|  *  - reset {Function} 重置表单字段的方法
 | |
|  */
 | |
| export default function useForm() {
 | |
|   const formRef = useTemplateRef("formRef");
 | |
|   /**
 | |
|    * @param {string} [message="请补全必填项!"] - 验证失败时显示的提示信息
 | |
|    * @returns {Promise<boolean>} 验证通过返回 resolve(true),失败 reject(false)
 | |
|    */
 | |
|   const validate = (message = "请补全必填项!") => {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       formRef.value.validate((valid) => {
 | |
|         if (valid) {
 | |
|           resolve(valid);
 | |
|         } else {
 | |
|           reject(valid);
 | |
|           ElMessage.warning(message);
 | |
|           setTimeout(() => {
 | |
|             const element = document.querySelectorAll(
 | |
|               ".el-form-item__error"
 | |
|             )[0];
 | |
|             element.scrollIntoView({
 | |
|               behavior: "smooth",
 | |
|               block: "center",
 | |
|             });
 | |
|           }, 100);
 | |
|         }
 | |
|       });
 | |
|     });
 | |
|   };
 | |
|   const reset = () => {
 | |
|     formRef.value.resetFields();
 | |
|   };
 | |
|   return { validate, formRef, reset };
 | |
| }
 |