在触发Javascript事件后,我正在尝试使用Javascript更新Liveview。Liveview必须显示一个带有从Javascript发送的值的<div>元素。
我的问题是:我应该如何将这些值从Javascript传递到Liveview?
我可能还需要Liveview在Javascript中发送的值。再说一次:我应该如何将这些值从Liveview传递到Javascript?
在Javascript中为liveview创建了一个Livesocket,但我看不到从那里获取或设置赋值的方法。从Liveview传送值/向Liveview传值的唯一方法似乎是通过DOM。例如:
<div id="lv-data" phx-hook="JavascriptHook"></div>let hooks = {};
hooks.JavascriptHook = {
mounted(){
this.el.addEventListener("jsEvent", (e) =>
this.pushEvent("jsEventToPhx", e.data, (reply, ref) =>
console.log("not sure what to do here")));
this.handleEvent("phxEventToJS", (payload) => console.log("data received: " + payload));
}
}在纯数据交换中使用带有虚拟<div>的DOM感觉很奇怪……
发布于 2020-07-18 00:06:08
您的LiveView模块是否实现为处理从前端发送的jsEventToPhx事件?您必须具有实现此消息的handle_event/3回调的父LiveView或LiveViewComponent。请参见:
https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:handle_event/3
例如(在您的LiveView模块中):
def handle_event("jsEventToPhx", params, socket) do
# Here the `params` variable is what you are sending form the
# client-side, so it will be `%{foo: "bar"}` if you
# follow the next example.
{:reply, %{hello: "world"}, socket}
end 然后在你的Hook中,你需要做的就是使用this.pushEvent
let hooks = {};
hooks.JavascriptHook = {
mounted(){
this.pushEvent("jsEventToPhx", {foo: "bar"}, (reply, ref) =>
// this will print `{hello: "world"}`
console.log(reply);
}
}
}当您想要将数据发送到LiveView并可选地立即接收响应时,这是一种方法。
如果您想从LiveView向客户端发送一些内容,那么过程会略有不同。在LiveView中,当从任何handle_event回调返回套接字时,您可以使用push_event,例如:
{:noreply, push_event(socket, "phxEventToJS", %{abc: "xyz"})}在你的Hook中,你可以订阅事件:
mounted(){
this.pushEvent("jsEventToPhx", {foo: "bar"}, (reply, ref) =>
// this will print `{hello: "world"}`
console.log(reply);
}
this.handleEvent("phxEventToJS", (payload) => {
// this will print `{abc: "xyz"}`
console.log(payload);
}
}检查客户端-服务器通信部分here可能是有用的。
https://stackoverflow.com/questions/62850762
复制相似问题