查看源代码
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>
套接字连接生命周期
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"}>