1、封装组件
1、规则校验一般基于form表单实现,因此需要给具体控件套一层form表单
新建组件input-required.vue,内容如下
html
<template>
<div>
<el-form ref="formRef" :model="form" :rules="formRules" label-width="0px" style="font-size:0.6vw">
<el-form-item :prop="this.propValue">
<el-input
v-model="value"
:placeholder="`请输入${labelValue}`"
autocomplete="off"
:disabled="isDisalbed"
@change="isValid"
></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
value: "",
form: {},
formRules: {}
};
},
// 子组件使用props来接收父组件内传过来的数据
props: ["propValue", "labelValue", "isDisalbed", "indexValue"],
created() {
// 给子组件的对象动态添加属性并设置属性值
this.$set(this.form, this.propValue, "");
this.$set(this.formRules, this.propValue, [
{ required: true, message: `${this.labelValue}不能为空`, trigger: "blur" }
]);
},
methods: {
// el-input失去焦点后会校验数据,空的话会提示,符合校验规则会触发父组件内方法更新视图数据
isValid() {
let flag = null;
this.form[this.propValue] = this.value;
this.$refs["formRef"].validate(valid => {
if (valid) {
flag = true;
this.$emit("updateData", this.form, this.indexValue);
} else {
flag = false;
}
});
// 把每次校验的结果返回给父组件
return flag;
}
},
};
</script>
<style>
</style>
2、组件使用
组件引入
html
import InputRequired from "/src/components/inputRequired/input-required.vue";
components: {InputRequired},
form表单里的table使用组件,isRequiredNumber(v-if="scope.row.isRequiredNumber == '0'")是否必填标识(看自己业务需求,这个必填在此处判断因为业务需求是可配置是否必填的,只做必填可以去掉该判断,正常使用input-required)
html
.......
<el-col :span="21">
<el-form-item label="资源" prop="resourcePrepare">
<el-table :data="resourceResult" :header-cell-style="{ background: '#f0f2f5' }">
<el-table-column align="center" prop="name" label="名称">
</el-table-column>
<el-table-column align="center" prop="num" label="数量">
<template slot-scope="scope">
<el-input v-if="scope.row.isRequiredNumber == '0'" v-model="scope.row.num"
placeholder="请输入内容">
</el-input>
<input-required v-else :ref="`requiredNum${scope.$index}`"
:propValue="'num'" :labelValue="'数量'" :isDisalbed="false"
:indexValue="scope.$index" @updateData="updateData"></input-required>
</template>
</el-table-column>
<el-table-column label="" width="90">
<template slot-scope="scope">
<span @click="delResourcePrepare(scope.row)"
class="el-icon-close txtClose"></span>
</template>
</el-table-column>
</el-table>
</el-form-item>
</el-col>
..........
提交表单做必填校验
html
submitForm() {
this.$refs["form"].validate(valid => {
let flag = true;
//循环判断table里的所有数据
for (let index = 0; index < this.resourceResult.length; index++) {
//资源数量是否必填(业务需要正常使用可去掉判断)
if (this.resourceResult[index].isRequiredNumber == '1') {
flag = flag && this.$refs[`requiredNum` + index].isValid();
}
}
if (!flag) {
//必填校验未通过,结束方法
return;
}
.....其他业务.....
});
},
大概就是这样了。。。