iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
Modern Web

Laravel Livewire:不用 Vue 跟 jQuery 居然也能讓 Laravel 的畫面動起來 ?!系列 第 29

Day 28 | 很像 Vue 的 AlpineJS(三): x-model

昨天還少講了一個最最最常用到的 x-model。如同他的樣子,跟 v-modelwire:model 一樣都是拿來綁定資料用的。由於前面也有介紹過 Livewire 的 wire:model 了,用起來跟 AlpineJS 的也都差不多,就邊看邊複習一下吧!

x-model

很方便的用於綁定<input>資料,當輸入時也會同步更新放在 x-model 中的值。當然在其他地方更新該值的話,放在<input>中的值也會隨之變化。

<div x-data="{ message: '' }">
    <input type="text" x-model="message">
 
    <span x-text="message">
</div>

x-model 能用在以下的元素:

  • <input type="text">
  • <textarea>
  • <input type="checkbox">
  • <input type="radio">
  • <select>

Text inputs

<input type="text" x-model="message">

Textarea inputs

<textarea x-model="message"></textarea>

Checkbox inputs

*單選

預設的話值會是 Boolean 型態。

<input type="checkbox" id="checkbox" x-model="show">

*多選

多選的話會存成陣列,但記得宣告時預設值要給陣列[],不然一樣會變 Boolean。

<div x-data="{ colors: [] }">
	<input type="checkbox" value="red" x-model="colors">
	<input type="checkbox" value="orange" x-model="colors">
	<input type="checkbox" value="yellow" x-model="colors">
</div>

Radio inputs

<input type="radio" value="yes" x-model="answer">
<input type="radio" value="no" x-model="answer">
 
Answer: <span x-text="answer"></span>

Select

<select x-model="color">
    <option>Red</option>
    <option>Orange</option>
    <option>Yellow</option>
</select>
 
Color: <span x-text="color"></span>

修飾符

這個單元不並陌生,因為我們在 Livewire 中的 wire:model 也有提到過類似的修飾功能。

.lazy

在預設的狀況下,在文字輸入匡 <input> 中每輸入一個字都會觸發一次 x-model 的更新,這樣會導致打字時畫面閃爍以及延遲等問題,不過我們能夠透過 .lazy 來改善這問題。.lazy 會在滑鼠聚焦移開輸入匡時才使 x-model 的值來更新。

<input type="text" x-model.lazy="title">

.number

可以使文字輸入匡<input>輸入的值自動轉為數字。輸入非數字的字元時將不會觸發更新。

<input type="text" x-model.number="age">

.debounce

..debounce 能在固定時間去觸發 x-model 的更新,預設為 250ms。

<input type="text" x-model.debounce="search">

如果要更改更新的頻率直接加在後在就可以了,如 x-model.debounce.1000ms

.throttle

跟上面的 .debounce 非常類似,但差別是 .throttle 是限制在更新後的指定秒數內不做更新的偵測,預設也是 250ms。

<input type="text" x-model.throttle="search">

因此假設設定為 1000ms 當你快速輸入 123 並在一千毫秒內多打幾個字變成 12345,結果值仍然會是 123。必須到一千毫秒後再繼續輸入成 123456 這時值才會跟著更新。


上一篇
Day27 - 很像 Vue 的 AlpineJS(二): 常用屬性
下一篇
Day 29 | 很像 Vue 的 AlpineJS(四): x-on
系列文
Laravel Livewire:不用 Vue 跟 jQuery 居然也能讓 Laravel 的畫面動起來 ?!34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言