const juris = new Juris({
services: {
contactForm: {
validate: (field, value) => {
let error = null;
if (field === 'name' && !value.trim()) {
error = '姓名是必填项';
} else if (field === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
error = '需要有效的邮箱';
}
return error;
},
submit: async (formData) => {
// 提交逻辑
return await api.sendContact(formData);
}
}
}
});
juris.enhance('.contact-form', ({ getState, setState, contactForm }) => ({
children: () => {
const form = getState('contactForm') || {};
const errors = getState('contactErrors') || {};
const isSubmitting = getState('isSubmitting') || false;
return [
{
form: {
onsubmit: async (e) => {
e.preventDefault();
setState('isSubmitting', true);
try {
await contactForm.submit(form);
setState('contactForm', {});
} catch (error) {
console.error('提交失败:', error);
} finally {
setState('isSubmitting', false);
}
},
children: [
{
div: {
className: 'field',
children: [
{ label: { text: '姓名' } },
{
input: {
value: form.name || '',
className: errors.name ? 'error' : '',
onblur: (e) => {
const error = contactForm.validate('name', e.target.value);
setState('contactErrors', { ...errors, name: error });
},
oninput: (e) => {
setState('contactForm', { ...form, name: e.target.value });
}
}
},
...(errors.name ? [{ span: { className: 'error', text: errors.name } }] : [])
]
}
},
{
div: {
className: 'field',
children: [
{ label: { text: '邮箱' } },
{
input: {
type: 'email',
value: form.email || '',
className: errors.email ? 'error' : '',
onblur: (e) => {
const error = contactForm.validate('email', e.target.value);
setState('contactErrors', { ...errors, email: error });
},
oninput: (e) => {
setState('contactForm', { ...form, email: e.target.value });
}
}
},
...(errors.email ? [{ span: { className: 'error', text: errors.email } }] : [])
]
}
},
{
button: {
type: 'submit',
disabled: isSubmitting || Object.keys(errors).length > 0 || !form.name || !form.email,
text: isSubmitting ? '发送中...' : '发送消息'
}
}
]
}
}
];
}
}));