问题现象:
当画面增加一个按钮,在输入框表示error状态下,按下按钮,error信息还是没有消失,即使在按下事件中已经设置了setCustomValidity()方法,还是没有起效。
【set value】按下↓↓↓
代码语言:javascript复制<template>
<lightning-card title="input demo">
<lightning-input type="text" value={inputValue} onchange={handleChangeEvent} required label="test input">
</lightning-input><br/>
<lightning-button label="set value" onclick={handleSetValueClick}></lightning-button>
</lightning-card>
</template>
代码语言:javascript复制import { LightningElement, track } from 'lwc';
export default class ExampleLwcInputRequired extends LightningElement {
@track inputValue = '';
handleChangeEvent(event) {
this.inputValue = event.detail.value;
if(this.template.querySelector('lightning-input').checkValidity()) {
this.template.querySelector('lightning-input').setCustomValidity('');
this.template.querySelector('lightning-input').reportValidity();
}
}
handleSetValueClick(event) {
this.inputValue = 'test';
if(this.template.querySelector('lightning-input').checkValidity()) {
this.template.querySelector('lightning-input').setCustomValidity('');
this.template.querySelector('lightning-input').reportValidity();
}
}
}
解决方法:添加setTimeout方法
代码语言:javascript复制import { LightningElement, track } from 'lwc';
export default class ExampleLwcInputRequired extends LightningElement {
@track inputValue = '';
handleChangeEvent(event) {
this.inputValue = event.detail.value;
if(this.template.querySelector('lightning-input').checkValidity()) {
this.template.querySelector('lightning-input').setCustomValidity('');
this.template.querySelector('lightning-input').reportValidity();
}
}
handleSetValueClick(event) {
this.inputValue = 'test';
window.clearTimeout(this.delayTimeout);
this.delayTimeout = setTimeout(() => {
if(this.template.querySelector('lightning-input').checkValidity()) {
this.template.querySelector('lightning-input').setCustomValidity('');
this.template.querySelector('lightning-input').reportValidity();
}
}, 1000);
}
}