點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-model with lazy Modifier

Sam Xiao's Avatar 2022-03-14

We can update the x-model when user focus aways from the input element or press enter.

Version

Alpine 3.9

x-model.lazy

lazy000

x-model is not updated unless user focus away from the input element or press enter.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="{ message: '' }">
    <input type="text" x-model.lazy="message" />
    <span x-text="message" />
  </body>
</html>

Line 9

<body x-data="{ message: '' }">
  <input type="text" x-model.lazy="message" />
  <span x-text="message" />
</body>
  • x.model.lazy : On text inputs, by default, x-model updates the property on every key-stroke. By adding the .lazy modifier, you can force an x-model input to only update the property when user focuses away from the input element

Conclusion

  • This is handy for things like real-time form-validation where you might not want to show an input validation error until the user tabs away from a field

Reference

Alpine, x-model.lazy