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
avatar: :originalHow 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)