Unexpected validity state when mounted
Vue version
v3.2.38
Link to minimal reproduction
Steps to reproduce
Make the input invalid and reload the page.
What is expected?
Data is loaded from localStorage
when mounted. The on-input method is called, to set another variable, if the data is valid. It should contain an empty string when reloading the page after setting the input to something invalid.
What is actually happening?
The lastValid
variable contains an invalid message
when reloading the page.
System Info
No response
Any additional comments?
No response
You can try to clear the value in input before excute this line. 'this.lastValid = document.querySelector('input').validity.valid ? this.message : '''
While excuting this line, you will find this value in input is your preset value 'OK World', it's legitimate, so this.lastValid will be assigned value of this.message but not ''. In result, the value of this.lastValid will always be equal to this.message and the value of localstorage.
Not sure how to clear the input as you suggested. But the problem probably is due to loading the data and directly calling the handleInput
function. This probably does not give Vue.js time do bind the data to the input field. Adding console output on line 12 gives:
console.log(document.querySelector('input').value, '#', this.message)
Output:
OK world # X
A workaround could be to use setTimeout(this.handleInput, 10)
in the mounted
function. Is there a cleaner way to do this?
handleInput() {
this.message = this.message.replaceAll(' ', '')
const input = document.querySelector('input')
input.value = this.message
this.lastValid = input.validity.valid ? this.message : ''
}
I think that.
Yes, the problem is that you didn't make the value of the input box equal to the value of this.message in time.