<template>
<el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
<el-form-item label="姓名" prop="name">
<el-input v-model="formData.name"></el-input>
</el-form-item>
<el-form-item label="手机号" prop="phone">
<el-input v-model="formData.phone"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="formData.age"></el-input>
</el-form-item>
<el-form-item label="学校" prop="school">
<el-input v-model="formData.school"></el-input>
</el-form-item>
<el-form-item label="性别" prop="gender">
<el-radio-group v-model="formData.gender">
<el-radio label="male">男</el-radio>
<el-radio label="female">女</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="地点" prop="location">
<el-radio-group v-model="locationType">
<el-radio label="province">选择省市区</el-radio>
<el-radio label="custom">手填地点</el-radio>
</el-radio-group>
<el-collapse v-model="collapseVisible" v-if="locationType === 'province'">
<!-- 省市区组件,这里使用Element Plus的级联选择器 -->
<el-cascader
v-model="formData.location"
:options="options"
placeholder="请选择省市区"
clearable
:props="{ value: 'code', label: 'name', children: 'children' }"
></el-cascader>
</el-collapse>
<el-input v-model="formData.location" v-else placeholder="请输入手填地点"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { ref } from 'vue';
import axios from 'axios';
import { ElForm, ElFormItem, ElInput, ElRadioGroup, ElRadio, ElButton, ElCollapse, ElCascader } from 'element-plus';
export default {
components: {
ElForm,
ElFormItem,
ElInput,
ElRadioGroup,
ElRadio,
ElButton,
ElCollapse,
ElCascader,
},
data() {
return {
formData: {
name: '',
phone: '',
age: '',
school: '',
gender: '',
location: '',
},
formRules: {
name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '手机号格式不正确', trigger: 'blur' },
],
age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
school: [{ required: true, message: '请输入学校', trigger: 'blur' }],
gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
location: [{ required: true, message: '请选择或输入地点', trigger: 'blur' }],
},
locationType: 'province', // 默认选择省市区
collapseVisible: false,
options: [
// 省市区数据,根据实际情况填写
{ code: '110000', name: '北京市', children: [...] },
{ code: '120000', name: '天津市', children: [...] },
// 其他省市区数据
],
};
},
methods: {
submitForm() {
this.$refs.form.validate((valid) => {
if (valid) {
// 表单验证通过,可以提交数据
axios.post('/api/submit', this.formData)
.then(response => {
console.log('提交成功', response);
// 根据实际需求处理提交成功后的逻辑
})
.catch(error => {
console.error('提交失败', error);
// 根据实际需求处理提交失败后的逻辑
});
} else {
return false;
}
});
},
},
};
</script>
<style>
/* 可选:自定义样式 */
</style>
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓