uview表单 hooks

在UViewUI库中,使用hooks封装表单二次可以让我们以更灵活的方式使用表单组件。下面是一个示例,展示如何将表单封装成hooks,并以JSON形式传递参数:
首先,我们可以创建一个自定义的Hook来处理表单逻辑。在这个例子中,我们创建了一个名为useFormData的Hook,它接收一个JSON对象作为参数,该对象包含了表单数据、表单项的配置等。

<script>
	import {ref , reactive} from 'vue';
	// 定义一个自定义 Hook
	const useFormData = (formConfig) => {
		const formData = reactive(formConfig.initialValues);
		const formErrors = reactive({});
		const validateField = (fieldName) => {
			const field = formConfig.fields[fieldName];
			if (!field) return false;
			const value = formData[fieldName];
			const validationResult =
				field.validator(value);
			if (!validationResult) {
				formErrors[fieldName] = field.errorMsg;
			} else {
				delete
				formErrors[fieldName];
			}
			return validationResult;
		};
		const validateForm = () => {
			let isValid = true;
			Object.keys(formConfig.fields).forEach((fieldName) => {
				isValid = validateField(fieldName) && isValid;
			});
			return
			isValid;
		};
		const setFieldValue = (fieldName, value) => {
			formData[fieldName] = value;
			delete formErrors[fieldName];
		};
		const getFieldValue = (fieldName) => {
			return formData[fieldName];
		};
		return {
			formData,
			formErrors,
			validateField,
			validateForm,
			setFieldValue,
			getFieldValue,
		};
	}
</script>

接下来,我们可以使用useFormData Hook 来创建表单组件。在组件中,我们可以通过传递一个JSON对象作为参数来配置表单。以下是一个示例:

<template>
  <u-form :model="formData" :rules="formConfig.rules">
    <u-form-item v-for="field in formConfig.fields" :key="field.name" :label="field.label" :prop="field.name">
      <template v-slot="{ item }">
        <u-input v-model="item.value" :placeholder="item.label">u-input>
      template>
    u-form-item>
    <u-button :disabled="!canSubmit" @click="submitForm">Submitu-button>
  u-form>
template>

<script>
import { useFormData } from './useFormData';
export default {
  setup() {
    const formConfig = {
      initialValues: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: 'Username is required', trigger: 'blur' },
        ],
        password: [
          { required: true, message: 'Password is required', trigger: 'blur' },
        ],
      },
      fields: {
        username: {
          name: 'username',
          label: 'Username',
        },
        password: {
          name: 'password',
          label: 'Password',
        },
      },
    };
    const { formData, validateForm, setFieldValue, getFieldValue } = useFormData(formConfig);
    const canSubmit = ref(true);
    const submitForm = () => {
      if (validateForm()) {
        console.log('Form data:', formData); // 在这里可以处理表单提交的逻辑,比如发送到服务器等操作。
      } else {
        canSubmit.value = false; 
      }
    };
  }
};
script>

你可能感兴趣的:(javascript,前端,vue.js)