error信息显示状态下按钮按下时error不消失问题

2021-11-25 14:32:01 浏览数 (1)

问题现象:

当画面增加一个按钮,在输入框表示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);
  }
}

【set value】按下↓↓↓

0 人点赞