设置一个组件用于动态添加删除el-form-item并添加表单验证
效果示例图
父组件中引入
<template>
<div class="app-container">
<dynamicAddItem ref="dynamicAdd"></dynamicAddItem>
<el-button @click="submitHandleFun">提交</el-button>
</div>
</template>
<script>
import dynamicAddItem from './dynamicAddItem.vue';
export default {
components: {
dynamicAddItem
},
data() {
return {};
},
mounted() {},
methods: {
submitHandleFun() {
this.$refs['dynamicAdd'].submitHandle();
console.log('[]', this.$refs['dynamicAdd'].dynamicValidateForm);
}
}
};
</script>
子组件dynamicAddItem.vue
<template>
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px">
<template v-for="(dynamic, index) in dynamicValidateForm.file">
<div :key="index">
<el-form-item :prop="'file.' + index + '.name'" :label="'用户名' + index" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
<el-input v-model="dynamic.name"></el-input>
</el-form-item>
<el-form-item :prop="'file.' + index + '.phone'" :label="'手机号' + index" :rules="[{ required: true, message: '请输入手机号', trigger: 'blur' }]">
<el-input v-model="dynamic.phone"></el-input>
</el-form-item>
<el-form-item><el-button @click.prevent="removeDynamic(dynamic)">删除</el-button></el-form-item>
</div>
</template>
<el-form-item><el-button @click="addDynamic">新增</el-button></el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
dynamicValidateForm: {
file: []
}
};
},
mounted() {},
methods: {
/**
* 提交动态表单数据
* **/
submitHandle() {
this.$refs['dynamicValidateForm'].validate(valid => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
/**
* 删除
* **/
removeDynamic(item) {
var index = this.dynamicValidateForm.file.indexOf(item);
if (index !== -1) {
this.dynamicValidateForm.file.splice(index, 1);
}
},
/**
* 新增
* **/
addDynamic() {
this.dynamicValidateForm.file.push({
name: '',
phone: ''
});
}
}
};
</script>
<style lang="scss" scoped></style>