當表單提交為空時,我試圖顯示錯誤訊息。但是,根據我單擊按鈕的次數顯示了相同的錯誤訊息。如何顯示唯一的錯誤訊息集而不是回圈?
這是它的外觀:
這是我嘗試檢查表單是否為空的代碼:
checkForm(){
if (this.staffName && this.designation && this.staffId && this.skills) {
return true;
}
if (!this.staffName) {
this.errors.push('Staff Name required.');
}
if (!this.designation) {
this.errors.push('Designation required.');
}
// if (this.password = '') {
// alert('Password required.');
// }
if(!this.staffId){
this.errors.push('Staff ID required.')
}
if(this.skills === []){
this.errors.push('Select at least one.');
}
if(this.errors.length){
return this.errors
}
else{
for (var staff of this.info){
if(staff.staff_id == this.staffId){
this.errors.push('This Staff exist! Please try again.');
return this.errors
}
else{
this.addStaff()
}
}
}
},
如果表單為空,這是我用來顯示錯誤的代碼:
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="(error, idx) in errors" :key="idx">{{ error }}</li>
</ul>
</p>
uj5u.com熱心網友回復:
我能想到的最簡單的方法:
每次觸發按鈕時清除陣列
你可以在template
標簽上做
<button
type="submit"
@click="errors = []"
>
或在checkForm
方法中
checkForm() {
this.errors = [] //make sure to place it at the top
}
提要
另外,不在您的問題范圍內,但您無法將陣列與===
, 甚至進行比較==
,它總是會回傳 false
我指的是這個
if(this.skills === []){
this.errors.push('Select at least one.');
}
由于您只想知道它是否為空,請.length
改用。但是如果你想比較像
[1, 2] == [1, 2]
它總是會回傳 false,但是您可以輕松地搜索解決方案,因為這是 JS 開發人員面臨的非常流行的問題
uj5u.com熱心網友回復:
您可以使用 Object 而不是將錯誤訊息推送到陣列,或者即使您想堅持錯誤,您也可以使用陣列include
函式來檢查它是否已經在陣列中。喜歡:
if (!this.errors.includes('Staff Name required.');
{
this.errors.push('Staff Name required.');
}
或者,如果您想使用 Object,您可以執行類似的操作
data() {
return {
errors: {
staf_name: null,
}
}
}
然后在你的代碼中你可以像這樣更新它this.errors.staf_name = '';
謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529924.html
標籤:Vue.js验证
上一篇:州和國會大廈的二維陣列,系統詢問用戶輸入,然后驗證答案
下一篇:字串/數字行為不正確的簡單驗證