验证vue js中的数据字段



我有根组件和子组件。我尝试在子组件中添加输入事件的验证数据,并在根组件中使用结果。在子中

<ValidationProvider
:bails="false"
:rules="validation"
slim
:vid="id"
ref="provider"
:name="id"
>
<textarea
:value="value"
@input="onInput($event)"
ref="area"
:rows="rows"
/>
</ValidationProvider>
extend('my', (value: string) => {
console.log('extend ' + value);
return !isNaN(+value);
});
});
$refs!: {
area: HTMLElement,
provider: InstanceType<typeof ValidationProvider>;
};
async onInput($event: any) {
const isTextareaValid = await this.$refs.provider.validate();
console.log('valid ', isTextareaValid.valid)
this.$emit('validation', isTextareaValid, this.$props.id); 
this.$emit('input', $event.target.value, this.$props.id);    
}

<Child
v-model="value"
validation="required|my"
@validation="check"
/>
<BaseButton
type="submit"
:disabled="!isValid"
:text="text"
/>
private isValid: boolean = false;
check(result: ValidationResult, id: string) {
this.isValid= result.valid;
}

现在,我的理解是,validate((在输入时使用以前的值。如何发送更改输入数据的验证结果?

我认为实现这一点的最佳方法是将输入的任何值发送到子组件中,并像一样将其发送到根

子组件

onInput($event: any) {
this.$emit('input', $event.target.value);   // you can only have two parameters here unless you use an object and de-structure it   

const isTextareaValid = this.$refs.provider.validate() // the await isn't necessary here as `isTextareaValid` returns a boolean and not a promise

this.$nextTick(() => { // this will wait for the next DOM update cycle to apply the validation check as Vue DOM updates are asynchronous
if (isTextareaValid) {
this.$emit('set-isValid-to-true');
} else {
this.$emit('set-isValid-to-false');
} 
}) 
}

根组件

<Child
v-model="value"
@set-isValid-to-true="setIsValidToTrue"
@set-isValid-to-false="setIsValidToFalse"
/>

private value = '';
private isValid: boolean = false;
public setIsValidToTrue() {
this.isValid = true;
}
public setIsValidToFalse() {
this.isValid = false;
}
<BaseButton
type="submit"
:disabled="!isValid"
:text="text"
/>

编辑----或者,你可以观察的变化

子组件

<ValidationProvider
...
>
<textarea
v-model="textValue"
ref="area"
:rows="rows"
/>
</ValidationProvider>
data() {
return {
textValue: ''
}
}
watch: {
textValue () {
const isTextareaValid = this.$refs.provider.validate() // the await isn't necessary here as `isTextareaValid` returns a boolean and not a promise
if (isTextareaValid) {
this.$emit('set-isValid-to-true');
} else {
this.$emit('set-isValid-to-false');
}  
}
}

根组件

<Child
@set-isValid-to-true="setIsValidToTrue"
@set-isValid-to-false="setIsValidToFalse"
/>

private isValid: boolean = false;
public setIsValidToTrue() {
this.isValid = true;
}
public setIsValidToFalse() {
this.isValid = false;
}
<BaseButton
type="submit"
:disabled="!isValid"
:text="text"
/>

相关内容

  • 没有找到相关文章

最新更新