檢視原始碼
phx-
HTML 屬性
在 Phoenix LiveView 範本中使用的特殊 HTML 屬性摘要。每個屬性都連結到其文件以供詳細查詢。
事件處理器
屬性值可以是
使用 phx-value-*
屬性將參數傳遞給伺服器。
使用 phx-debounce
和 phx-throttle
來控制事件的頻率。
範例
lib/hello_web/live/hello_live.html.heex
<button type="button" phx-click="click" phx-value-user={@current_user.id}>Click Me</button>
<button type="button" phx-click={JS.toggle(to: "#example")}>Toggle</button>
容器元件上
LiveView 在使用者互動前套用 phx-no-feedback
CSS 類別。
lib/hello_web/live/hello_live.html.heex
<form phx-change="validate" phx-submit="save">
<input type="text" name="name" phx-debounce="500" phx-throttle="500" />
<button type="submit" phx-disable-with="Saving...">Save</button>
</form>
Socket 連線生命週期
lib/hello_web/live/hello_live.html.heex
<div id="status" class="hidden" phx-disconnected={JS.show()} phx-connected={JS.hide()}>
Attempting to reconnect...
</div>
DOM 元件生命週期
lib/hello_web/live/hello_live.html.heex
<div
id="iframe-container"
phx-mounted={JS.transition("animate-bounce", time: 2000)}
phx-remove={JS.hide(transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"})}
>
<button type="button" phx-click={JS.exec("phx-remove", to: "#iframe-container")}>Hide</button>
<iframe id="iframe" src="https://example.com" phx-update="ignore"></iframe>
</div>
用戶端掛勾
用戶端掛勾使用 this.pushEvent
和 this.handleEvent
提供用戶端和伺服器之間的雙向通訊,用來傳送和接收事件。
lib/hello_web/live/hello_live.html.heex
<div id="example" phx-hook="Example">
<h1>Events</h1>
<ul id="example-events"></ul>
</div>
assets/js/app.js
let Hooks = {}
Hooks.Example = {
// Callbacks
mounted() { this.appendEvent("Mounted") },
beforeUpdate() { this.appendEvent("Before Update") },
updated() { this.appendEvent("Updated") },
destroyed() { this.appendEvent("Destroyed") },
disconnected() { this.appendEvent("Disconnected") },
reconnected() { this.appendEvent("Reconnected") },
// Custom Helper
appendEvent(name) {
console.log(name)
let li = document.createElement("li")
li.innerText = name
this.el.querySelector("#example-events").appendChild(li)
}
}
let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks})
追蹤靜態素材
lib/hello_web/components/layouts/root.html.heex
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>