前言:
vue中使用element实现form表单动态添加email效果
效果:
实现步骤:
实现源代码:
<template>
<div>
<el-form ref="dynamicValidateForm" :model="dynamicValidateForm" label-width="100px" class="demo-dynamic">
<el-form-item
v-for="(domain, index) in dynamicValidateForm.domains"
:key="domain.key"
:label="'域名' + index"
:prop="'domains.' + index + '.value'"
:rules="[
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
]"
>
<el-input v-model="domain.value" style="width:200px;margin-right:10px;"></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>
</div>
</template>
<script>
export default {
components: {},
props: [],
data() {
return {
dynamicValidateForm: {
domains: [{
value: ''
}],
email: ''
}
}
},
watch: {},
created() {
},
mounted() {
},
beforeDestroy() {
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!')
} else {
console.log('error submit!!')
return false
}
})
},
resetForm(formName) {
this.$refs[formName].resetFields()
},
removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item)
if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1)
}
},
addDomain() {
//新增加校验方法1,页面上的input框不能有空值,这里是因为我的form表单只有email,如果不光是email的话就不建议这样来判断了
this.$refs['dynamicValidateForm'].validate((valid) => {
if (valid) {
this.dynamicValidateForm.domains.push({
value: '',
key: Date.now()
})
}
})
//新增加校验方法2,页面有任何一个空的都不行
let isPass = true //是否可以执行方法
this.dynamicValidateForm.domains.forEach(item => {
if(item.value === ''){
isPass = false
}
})
if(isPass){
this.dynamicValidateForm.domains.push({
value: '',
key: Date.now()
})
}
}
}
}
</script>
<style lang='scss' scoped>
</style>