Vue3使用el-form实现登录、注册功能,且进行表单验证(Element Plus中的el-form)
<template>
<el-form :model="form" :rules="rules" ref="loginForm">
<el-form-item prop="username">
<el-input v-model="form.username" placeholder="Username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model="form.password" placeholder="Password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('loginForm')">Login</el-button>
<el-button @click="resetForm('loginForm')">Reset</el-button>
</el-form-item>
</el-form>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
const form = reactive({
username: '',
password: ''
});
const loginForm = ref(null);
const validateUsername = (rule, value, callback) => {
if (value.length < 6) {
callback(new Error('Username must be at least 6 characters long'));
} else {
callback();
}
};
const validatePassword = (rule, value, callback) => {
if (value.length < 6) {
callback(new Error('Password must be at least 6 characters long'));
} else {
callback();
}
};
const rules = {
username: [
{ required: true, message: 'Please input username', trigger: 'blur' },
{ validator: validateUsername, trigger: 'blur' }
],
password: [
{ required: true, message: 'Please input password', trigger: 'blur' },
{ validator: validatePassword, trigger: 'blur' }
]
};
const submitForm = (formName) => {
loginForm.value.validate((valid) => {
if (valid) {
ElMessage.success('Login Success');
// 实际项目中这里会调用登录API
} else {
ElMessage.error('Login Fail');
return false;
}
});
};
const resetForm = (formName) => {
loginForm.value.resetFields();
};
</script>
这个代码实例展示了如何在Vue 3中使用Element Plus的el-form
组件来创建一个登录表单,并使用表单验证规则。它包括了用户名和密码的验证,以及登录和重置表单的方法。这个例子简洁明了,并且提供了一个很好的表单验证实践。
评论已关闭