點燈坊

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

Using x-model with number Modifier

Sam Xiao's Avatar 2022-03-14

By default, any data stored in a property via x-model is stored as a string. To force Alpine to store the value as a JavaScript number, add the .number modifier.

Version

Alpine 3.9

x-model.number

number000

The default value of x-model is an empty String. It is converted to a Number automatically.

<!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="{ age: '' }">
    <input type="text" x-model.number="age" />
    <span x-text="typeof age" />
  </body>
</html>

Line 9

<body x-data="{ age: '' }">
  <input type="text" x-model.number="age" />
  <span x-text="typeof age" />
</body>
  • x-model.number : convert to Number if possible

Conclusion

  • This is handy if the data is always Number. We don’t have to convert String to Number again

Reference

Alpine, x-model.number