LiveVue
1.0
Event Handling
Two ways to send events from Vue to LiveView: Phoenix bindings like
phx-click
and programmatic pushEvent()
via the useLiveVue()
hook.
What this example shows
defmodule MyAppWeb.EventsLive do
use MyAppWeb, :live_view
def render(assigns) do
~H"""
<.vue
messages={@messages}
v-component="Events"
v-socket={@socket}
/>
"""
end
def mount(_params, _session, socket) do
{:ok, assign(socket, messages: [])}
end
def handle_event("add_message", %{"text" => text}, socket) do
message = %{id: System.unique_integer([:positive]), text: text, from: "pushEvent"}
{:noreply, update(socket, :messages, &[message | &1])}
end
def handle_event("phx_click_message", %{"text" => text}, socket) do
message = %{id: System.unique_integer([:positive]), text: text, from: "phx-click"}
{:noreply, update(socket, :messages, &[message | &1])}
end
def handle_event("clear", _params, socket) do
{:noreply, assign(socket, :messages, [])}
end
end
How it works
1 Phoenix bindings work directly in Vue
Standard Phoenix event bindings like
phx-click
work in Vue templates. Pass data with
phx-value-*
attributes.
<button phx-click="phx_click_message" phx-value-text="Hello!">
2 useLiveVue() provides the Phoenix hook
The useLiveVue()
composable returns the Phoenix LiveView hook instance.
Use it for programmatic event handling.
const live = useLiveVue()
3 pushEvent() sends data to LiveView
Call
pushEvent(name, payload)
to send events programmatically. This is useful when you need to send
computed values or handle complex interactions.
live.pushEvent("add_message", { text: inputText.value })
4 handle_event receives both event types
LiveView handles events from both
phx-click
and pushEvent()
the same way. The params contain the payload you sent.
def handle_event("add_message", %{"text" => text}, socket)