LiveVue
1.0
Custom Encoder
Control how structs are encoded to JSON using the
LiveVue.Encoder
protocol. Derive for simple cases, implement custom logic when needed.
What this example shows
defmodule MyAppWeb.EncoderLive do
use MyAppWeb, :live_view
defmodule Business do
@derive LiveVue.Encoder
defstruct [:name, :industry]
end
defmodule UserProfile do
defstruct [:name, :avatar_url, :avatar_original_url, :business]
end
defimpl LiveVue.Encoder, for: UserProfile do
def encode(profile, opts) do
avatar_url =
if Keyword.get(opts, :avatar) == :original,
do: profile.avatar_original_url,
else: profile.avatar_url
%{
name: profile.name,
avatar_url: avatar_url,
business: LiveVue.Encoder.encode(profile.business, opts)
}
|> LiveVue.Encoder.encode(opts)
end
end
def render(assigns) do
~H"""
<.vue
profile={@profile}
profile_original={LiveVue.Encoder.encode(@profile, avatar: :original)}
v-component="Encoder"
v-socket={@socket}
/>
"""
end
def mount(_params, _session, socket) do
profile = %UserProfile{
name: "Ada Lovelace",
avatar_url: "https://api.dicebear.com/9.x/personas/png?seed=Lovelace&size=32",
avatar_original_url: "https://api.dicebear.com/9.x/personas/png?seed=Lovelace&size=256",
business: %Business{name: "Analytical Engine Co.", industry: "Computing"}
}
{:ok, assign(socket, profile: profile)}
end
end
How it works
1 Derive for simple structs
Use
@derive LiveVue.Encoder
to automatically encode all struct fields. Add
only:
or except:
to control which fields are included.
defmodule Business do
@derive LiveVue.Encoder
defstruct [:name, :industry]
end
2 Custom implementations with options
Implement the protocol directly when you need custom encoding logic. The
opts
parameter lets you change behavior at runtime.
defimpl LiveVue.Encoder, for: UserProfile do
def encode(profile, opts) do
avatar_url =
if Keyword.get(opts, :avatar) == :original,
do: profile.avatar_original_url,
else: profile.avatar_url
%{
name: profile.name,
avatar_url: avatar_url,
business: encode(profile.business, opts)
}
end
end
3 Pass options when encoding
Call
LiveVue.Encoder.encode/2
explicitly in your template to pass custom options. This lets you control
encoding per-prop.
<.vue
profile={@profile}
profile_with_original_avatar={LiveVue.Encoder.encode(@profile, avatar: :original)}
v-component="UserProfile"
v-socket={@socket}
/>
4 Nested structs are encoded recursively
When encoding nested structs, call
LiveVue.Encoder.encode/2
on nested values to ensure they're properly encoded. Options are passed through.
business: LiveVue.Encoder.encode(profile.business, opts)