介绍
本示例以字符串字段为业务场景,将输入框用element-plus
的组件实现了一遍,vue组件内在onMounted
生命周期内将ElForm
表单实例通过ts组件内提供到props
的setFormInstance
方法设置到了ts组件的属性formInstance
上,这样就可以在ts组件校验方法validator()
触发的时候直接调用表单组件实例formInstance
的校验方法validate()
适用场景
- 当前字段存储了动态表单的配置json,vue组件内自行实现了一套表单渲染逻辑,需要在vue组件和ts组件内同时触发校验
参考文档
示例代码
ts组件
import {
BaseFieldWidget,
FormStringFieldSingleWidget,
isValidatorSuccess,
ModelFieldType,
SPI,
ValidatorInfo,
ViewType,
Widget
} from '@kunlun/dependencies';
import { FormInstance } from 'element-plus';
import MyFormStringField from './MyFormStringField.vue';
@SPI.ClassFactory(
BaseFieldWidget.Token({
viewType: [ViewType.Form, ViewType.Search],
ttype: ModelFieldType.String,
widget: 'Input',
model: 'resource.k2.Model0000000109',
name: 'code',
})
)
export class MyFormStringFieldWidget extends FormStringFieldSingleWidget {
public initialize(props) {
super.initialize(props);
this.setComponent(MyFormStringField);
return this;
}
/**
* ElementPlus的表单vue组件实例
* @private
*/
private formInstance?: FormInstance;
@Widget.Method()
private setFormInstance(formInstance: FormInstance | undefined) {
this.formInstance = formInstance;
}
/**
* 字段校验方法
*/
public async validator(): Promise<ValidatorInfo> {
const validRes = await this.formInstance?.validate((valid, fields) => {});
console.log('validRes', validRes)
if (!validRes) {
return this.validatorError('校验失败');
}
const res = await super.validator();
if (!isValidatorSuccess(res)) {
return res;
}
if (this.value == null) {
return this.validatorSuccess();
}
return this.validateLength(this.value);
}
}
vue组件
<template>
<ElForm ref="formInstance" :model="model" :rules="rules">
<ElFormItem label="编码" prop="code">
<ElInput v-model="model.code" @input="onValueChange"></ElInput>
</ElFormItem>
</ElForm>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted, watch } from 'vue';
import { ElForm, ElFormItem, ElInput, FormInstance } from 'element-plus';
export default defineComponent({
name: 'MyFormStringField',
components: {
ElForm,
ElFormItem,
ElInput
},
props: ['value', 'setFormInstance', 'onChange'],
setup(props) {
const formInstance = ref<FormInstance>();
const model = ref({ code: '' });
const rules = reactive({
code: [
{ required: true, message: '必填', trigger: 'blur' },
]
});
function onValueChange() {
props.onChange?.(model.value.code);
}
onMounted(() => {
props.setFormInstance?.(formInstance.value);
});
watch(props.value, () => {
model.value.code = props.value;
});
return {
formInstance,
model,
rules,
onValueChange
}
}
});
</script>
页面校验效果查看
Oinone社区 作者:nation原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/17094.html
访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验