页面
首先需要在表单配置model、ref、rules,el-form-item中放prop
<el-form :model="form" label-width="0" ref="formRef" :rules="rules">
<el-form-item label="" prop="username">
<el-input v-model="form.username" :prefix-icon="User" />
</el-form-item>
<el-form-item label="" prop="password">
<el-input
v-model="form.password"
:prefix-icon="Lock"
show-password
/>
</el-form-item>
<el-form-item label="">
<el-button
class="loginBtn"
type="primary"
:loading="btnLoading"
@click="loginClick"
>
登录
</el-button>
</el-form-item>
</el-form>
script
let form = reactive({
username: 'admin',
password: '111111',
})
const formRef = ref()
const btnLoading = ref(false)
const rules = {
username: [
{ required: true, message: '请输入账号', trigger: 'blur' },
{ min: 5, message: '账号不能少于五位', trigger: 'blur' },
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 5, message: '密码不能少于五位', trigger: 'blur' },
],
}
const loginClick = () => {
formRef.value.validate(async (valid: any, fields: any) => {
if (valid) {
btnLoading.value = true
try {
await userStore.userLogin(form) // 接口
btnLoading.value = false
ElNotification({
title: `${tool.getTimeType()}好`,
message: '登录成功',
})
await router.push('/')
} catch (error) {
btnLoading.value = false
ElNotification({
title: '登录失败',
message: (error as Error).message,
})
}
} else {
btnLoading.value = false
console.log('error submit!', fields)
}
})
}
看着简单,少一点休想校验 (ˉ▽ˉ;)…