Subscribe on changes!

Unexpected validity state when mounted

avatar
Sep 3rd 2022

Vue version

v3.2.38

Link to minimal reproduction

https://sfc.vuejs.org/#eNp9U8lu2zAQ/ZUpL3LQWAKaS2E4qXMMfPAhRU+6MOLEZkuRDDmyaxj69w612FaCBhCg2TjvzXYSj97n+wbFQixjFbSnh9LiX+8CgcJX2RiCU2kBlCQ5u+llgIDUBDtqADXGKLe4gGyzhoMLRmW3o8/ISL+k0Yq9o7VNv7ZTaqSdU3ExJttJqww+Wd/QBQ+AdjrmAwzcT9Q8oDeywkdjZhlktwxzM3l2ZsAPlauaGi3lbw2G4zMarMiFWaYTYHaT71OcpmMvwI8pcCrhQwUHSdXuzH8IveZuXCXNM8MkshHpibCeZVIF3dRjaqZ9jTQUcN0n11hCdcm7l6GbChc1Adj+B2BIqV9h1j37cg+2MWbaqkuHU0zv6hyTsXSsSsvfsjhvDSuRjgZZZJQUCCdwDRlteTGss9iX07kW2vYNPsGLCwrDvHLGhQVvlkphnHfIxTJXwwOmPvPSP/w8eoTo0uZou4VIMlASDpp2UIrNuhQ8jtM4CmhbKJJ+2YO2XRY+Jadlz3Q/r51Cc1+K4VEpoFuqnTPMju3IW8HGVRfP+rQhgom/NTqx95IIg+WQzTr/WoqCcZbFuQZxK3Sd7mteS5//js7y7XUjLQdH7Oj3vS8FH2fSGZDIx0VRNNb/2eaVq4sV+4rAa6FrnCtXr+7yb/nd90LpSNf2HGM9fwnuEDEwYimGK+ySF2zcc/8DWi4Uw6dg72IngO98H0DHpRHtP0wmgE8=

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

avatar
Sep 3rd 2022

You can try to clear the value in input before excute this line. 'this.lastValid = document.querySelector('input').validity.valid ? this.message : '''

avatar
Sep 3rd 2022

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.

avatar
Sep 3rd 2022

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
avatar
Sep 3rd 2022

A workaround could be to use setTimeout(this.handleInput, 10) in the mounted function. Is there a cleaner way to do this?

avatar
Sep 3rd 2022
 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.

avatar
Sep 3rd 2022

Yes, the problem is that you didn't make the value of the input box equal to the value of this.message in time.

avatar
Sep 3rd 2022

I'll cover this into a discussion as it's not a bug.