Element中表單驗證的基本方法可參照 官方說明
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
<el-form-item
prop="email"
label="郵箱"
:rules="[
{ required: true, message: '請輸入郵箱地址', trigger: 'blur' },
{ type: 'email', message: '請輸入正確的郵箱地址', trigger: 'blur,change' }
]"
>
<el-input v-model="dynamicValidateForm.email"></el-input>
</el-form-item>
<el-form-item
v-for="(domain, index) in dynamicValidateForm.domains"
:label="'域名' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="{
required: true, message: '域名不能為空', trigger: 'blur'
}"
>
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">刪除</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
<el-button @click="addDomain">新增域名</el-button>
<el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
dynamicValidateForm: {
domains: [{
value: ''
}],
email: ''
}
};
},
methods: {}
}
</script>
這是官方的一個例子玲躯,例子中包含一個表單,數(shù)據(jù)結(jié)構(gòu)是:
dynamicValidateForm:{
email:'', // 基本屬性
domains:[] // 數(shù)組
}
"域名"表單項用了一個v-for來動態(tài)新增鳄乏,需要注意的是:prop的值府蔗,常見的錯誤信息是"Error: please transfer a valid prop path to form item!",例子中使用的是'domains.' + index + '.value'汞窗,其實和prop="email"類似,用鏈?zhǔn)浇Y(jié)構(gòu)表示赡译。
如果 仲吏,數(shù)據(jù)的結(jié)構(gòu)是
dynamicValidateForm:{}
domains:[]
要整理成以上的結(jié)構(gòu)(如果一定要這樣實現(xiàn)),容易有坑!裹唆!
<el-form-item
v-for="(domain, index) in dynamicValidateForm.domains"
:label="'域名' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="{
required: true, message: '域名不能為空', trigger: 'blur'
}"
>
<!-- 選擇框-->
<el-select filterable v-model="domain.value" placeholder="請選擇" >
<el-option
v-for="item in domain.options"
:key="item.value"
:label="item.label"
:value="item.value" >
</el-option>
</el-select>
</el-form-item>
<script>
export default {
data () {
dynamicValidateForm:{
email:'', // 基本屬性
domains:[] // 數(shù)組
}
},
created () {
this.id = this.$route.params.id
// 有ID誓斥,則是編輯頁面,否則是新增頁面
if(this.id){
this.getData()
}
}许帐,
methods: {
getData(){
getData(this.id).then(res => {
this.dynamicValidateForm = res.data.dynamicValidateForm
this.dynamicValidateForm.domains = res.data.domains
})
}
}
}
</script>
進(jìn)入頁面后劳坑,發(fā)現(xiàn)進(jìn)入編輯頁面后,選擇框選擇后沒反應(yīng)了成畦,頁面也沒有報錯~~~
為什么呢距芬?
找了半天原因,找了<select>的文檔循帐,沒發(fā)現(xiàn)問題 ~~~~~
終于框仔,
this.dynamicValidateForm = res.data.dynamicValidateForm this.dynamicValidateForm.domains = res.data.domains
這兩行代碼,第一行由于res.data.dynamicValidateForm就是一個object拄养,它并沒有domains這個屬性离斩,賦值后,dynamicValidateForm 中也沒有domains這個屬性了瘪匿。而第二行代碼跛梗,賦值給domains ,沒有報錯棋弥,可是使用的時候核偿,這個屬性卻不會生效。而<select>綁定的可是domains 中的值嘁锯。宪祥。
解決方法:
this.$set(this.dynamicValidateForm,'domains ',res.data.domains)
在vue.js中,給對象賦值家乘,最好還是使用$set