// 弹出Dialog对话框按钮
<el-button type="primary" @click="dialogTableVisible = true">添加用户</el-button>
@close="addDialogClose" // 关闭弹框的回调(用于清空表单)
:visible.sync="dialogTableVisible" // 弹框是否开启
:close-on-click-modal="false" // 是否可以通过点击任意位置关闭Dialog弹框
<!-- 添加用户弹框 -->
<el-dialog
title="添加用户"
@close="addDialogClose"
:visible.sync="dialogTableVisible"
:close-on-click-modal="false"
>
<!-- 添加用户的表单 -->
<el-form ref="addFormRef" :rules="rulesAddUser" :model="addUser" label-width="100px">
<el-form-item prop="username" label="用户姓名">
<el-input v-model="addUser.username"></el-input>
</el-form-item>
<el-form-item prop="password" label="用户密码">
<el-input v-model="addUser.password"></el-input>
</el-form-item>
<el-form-item prop="email" label="用户邮箱">
<el-input v-model="addUser.email"></el-input>
</el-form-item>
<el-form-item prop="mobile" label="用户手机号">
<el-input v-model="addUser.mobile"></el-input>
</el-form-item>
<el-form-item>
<el-button @click="dialogTableVisible = false">取消</el-button>
<el-button type="primary" @click="onAddUser">确定</el-button>
</el-form-item>
</el-form>
</el-dialog>
data() {
// 自定义一个手机号验证规则
var checkMoblie = (rule, value, callback) => {
if (!value.trim()) {
return callback(new Error('请输入手机号'))
}
if (!/^1[34578]\d{9}$/.test(value)) {
return callback(new Error('手机号有误!请重填'))
} else {
callback()
}
}
return {
dialogTableVisible: false, // 添加用户弹框
// 添加用户
addUser: {
username: '',
password: '',
email: '',
mobile: ''
},
// 验证规则
rulesAddUser: {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入用户密码', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{
type: 'email',
message: '请输入正确的邮箱地址',
trigger: ['blur', 'change']
}
],
mobile: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ validator: checkMoblie, trigger: 'blur' }
]
}
}
}
或者对单行进行校验
<el-form-item
prop="email"
label="邮箱"
:rules="[
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
]"
>
<el-input v-model="addUser.email"></el-input>
</el-form-item>
methods: {
// 关闭弹框的回调
addDialogClose() {
this.$refs.addFormRef.resetFields() // 清空表单
},
// 点击添加用户
onAddUser() {
this.$refs.addFormRef.validate(async valid => {
if (!valid) return null // 如果验证失败就不往下继续执行
const { data: res } = await this.$http.post('users', this.addUser)
if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
this.$message.success('添加成功')
this.dialogTableVisible = false // 关闭弹框
this.$refs.addFormRef.resetFields() // 清空表单
this.getUserList() // 重新调用,刷新表单
})
},
网友评论