72 lines
2.4 KiB
Vue
72 lines
2.4 KiB
Vue
<template>
|
||
<div class="aa-formmodal-mask" v-if="visible" @click.self="$emit('cancel')">
|
||
<div class="aa-formmodal">
|
||
<div class="aa-formmodal-head">
|
||
<span>{{ title }}</span>
|
||
<button class="aa-formmodal-close" @click="$emit('cancel')">×</button>
|
||
</div>
|
||
<div class="aa-formmodal-body">
|
||
<div class="aa-form-row" v-for="f in fields" :key="f.key">
|
||
<label class="aa-form-label"><span class="req" v-if="f.required">*</span>{{ f.label }}</label>
|
||
<input
|
||
class="aa-form-input"
|
||
:class="{ 'is-error': errors[f.key] }"
|
||
:value="form[f.key]"
|
||
:placeholder="f.placeholder"
|
||
@input="onInput(f.key, $event)"
|
||
/>
|
||
<div class="aa-form-err" v-if="errors[f.key]">{{ errors[f.key] }}</div>
|
||
</div>
|
||
</div>
|
||
<div class="aa-formmodal-foot">
|
||
<button class="aa-btn" @click="$emit('cancel')">取消</button>
|
||
<button class="aa-btn aa-btn--primary" @click="submit">提交</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup>
|
||
import { ref, watch } from 'vue';
|
||
|
||
const props = defineProps({
|
||
visible: { type: Boolean, default: false },
|
||
title: { type: String, default: '表单' },
|
||
fields: {
|
||
type: Array,
|
||
default: () => [
|
||
{ key: 'name', label: '姓名', required: true, placeholder: '请输入姓名' },
|
||
{ key: 'email', label: '邮箱', required: true, placeholder: 'name@example.com' },
|
||
{ key: 'role', label: '角色', placeholder: '如:管理员' }
|
||
]
|
||
},
|
||
value: { type: Object, default: () => ({}) }
|
||
});
|
||
const emit = defineEmits(['cancel', 'submit']);
|
||
|
||
const form = ref({ ...props.value });
|
||
const errors = ref({});
|
||
watch(
|
||
() => props.visible,
|
||
(v) => { if (v) { form.value = { ...props.value }; errors.value = {}; } }
|
||
);
|
||
|
||
function onInput(key, e) {
|
||
form.value[key] = e.target.value;
|
||
if (errors.value[key]) delete errors.value[key];
|
||
}
|
||
function submit() {
|
||
const errs = {};
|
||
props.fields.forEach((f) => {
|
||
const v = (form.value[f.key] || '').trim();
|
||
if (f.required && !v) errs[f.key] = f.label + '不能为空';
|
||
if (f.key === 'email' && v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) errs[f.key] = '邮箱格式不正确';
|
||
});
|
||
if (Object.keys(errs).length) { errors.value = errs; return; }
|
||
emit('submit', { ...form.value });
|
||
emit('cancel');
|
||
}
|
||
</script>
|
||
|
||
<style src="./FormModal.css"></style>
|