1. 基本三大組件
<el-form>
<el-form-item>
<el-input/>
</el-form-item>
</el-form>
2. 資料收集
在 el-form 上面指定 model,在 el-input 組件加 v-model 進行雙向資料系結
3. 資料校驗
在el-form 上面指定 rules 校驗規則,在 el-form-item 組件加 prop,指定要校驗的欄位
<template>
<div id="app">
<!-- 卡片組件 -->
<el-card class="login-card">
<!-- 登錄表單 -->
<el-form style="margin-top: 50px" :model="loginForm" :rules="loginRules">
<el-form-item prop="mobile">
<el-input v-model="loginForm.mobile" placeholder="請輸入手機號" />
</el-form-item>
<el-form-item prop="password">
<el-input v-model="loginForm.password" placeholder="請輸入密碼" />
</el-form-item>
<el-form-item>
<el-button type="primary" style="width: 100%">登錄</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
loginForm: {
mobile: "",
password: ""
},
loginRules: {
mobile: [
{ required: true, message: "手機號不能為空", trigger: "blur" },
{
pattern: /^1[3-9]\d{9}$/,
message: "請輸入正確的手機號",
trigger: "blur"
}
],
password: [
{ required: true, message: "密碼不能為空", trigger: "blur" },
{
min: 6,
max: 16,
message: "密碼應為6-16位的長度",
trigger: "blur"
}
]
}
};
}
};
</script>
3.1自定義校驗規則
<script>
export default {
name: 'App',
data() {
const customValidatorMobile = (rule, value, callback) => {
// 無論符不符合規則,都要呼叫 callback,只不過,校驗失敗要傳遞一個錯誤物件,校驗成功不用傳遞任何內容
value[2] === '9' ? callback() : callback(new Error('第三個數字必須是 9'))
}
return {
loginRules: {
mobile: [
{
validator: customValidatorMobile,
trigger: 'blur'
}
],
}
}
}
}
</script>
3.2 表單預校驗,當所有的內容都符合規則了,才去呼叫對應的介面
<el-form ref="loginFormRef"></el-form>
async handleSubmit() {
this.$refs['loginFormRef'].validate(function(valid) {
if (!valid) return console.log('失敗')
// 發請求呼叫介面
})
// 這里不能直接呼叫介面
/* this.$refs['loginFormRef'].validate().then(() => {
// 發請求呼叫介面
}).catch(() => {
// 預校驗失敗,彈框提示
}) */
/* try {
await this.$refs['loginFormRef'].validate()
// 預校驗通過呼叫介面
} catch (e) {
// 預校驗失敗,彈框提示
console.log(e.message, 23)
} */}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333819.html
標籤:其他
