iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0

htmx

正如 htmx 官網介紹的四個 why:

# Why should only <a> & <form> be able to make HTTP requests?

# Why should only click & submit events trigger them?

# Why should only GET & POST methods be available?

# Why should you only be able to replace the entire screen?

htmx 要擺脫這些限制,透過自訂屬性讓 HTML 就可以做到

範例:

<script src="https://unpkg.com/htmx.org@2.0.2"></script>
  
<button hx-post="/clicked" hx-swap="outerHTML">
Click Me
</button>

分別使用了 hx-posthx-swap 屬性,當使用者點擊按鈕時,會發送一個 AJAX 請求到 /clicked,並將 button 置換成 Response 的 HTML。

*AJAX 相關有:hx-gethx-posthx-puthx-patchhx-delete,後面都是接 URL

Swapping

htmx 預設會使用 innerHTML 來替換掉目標元素的內容,替換方式包含:

  • innerHTML
  • outerHTML
  • afterbegin
  • beforebegin
  • beforeend
  • afterend
  • delete
  • none

*就像講者提到的,htmx 受眾較偏向於後端需開發 Single Page 的情境


Alpine.js

輕量的前端框架

範例:

<div x-data="{ count: 0 }">
    <button x-on:click="count++">Increment</button>
 
    <span x-text="count"></span>
</div>

宣告資料

<div x-data="{ count: 0 }">

使用 x-data

監聽事件

<button x-on:click="count++">Increment</button>

使用 x-on,當事件觸發時,Alpine 會去 x-data 找資料,執行 count++

更新畫面

<span x-text="count"></span>

使用 x-text,用來設定元素的內容

*Alpine 目前有 15 個 attributes、6 個 properties 以及 2 個 methods,適用於一般的前端互動和樣式


參考資源

【網站前端開發學習手札】Alpine-羽量級JS框架(上篇)


上一篇
[Hello World] Shadcn UI
系列文
那些經過腦海一瞬的關鍵字們13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言