首页 > 解决方案 > 如何从 javascript 与 liveview 正确通信

问题描述

我正在尝试在触发 Javascript 事件后使用 Javascript 更新 Liveview。Liveview 必须显示<div>带有从 Javascript 发送的一些值的元素。

我的问题是:我应该如何将这些值从 Javascript 传递到 Liveview?

我可能还需要 Liveview 在 Javascript 中发送的值。再说一遍:我应该如何将这些值从 Liveview 传递给 Javascript?

在 Javascript 中创建了一个 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));
  }
}

这感觉很奇怪,必须使用带有假人的 DOM 来<div>进行纯粹的数据交换......

标签: javascriptelixirphoenix-frameworkphoenix-live-view

解决方案


您的LiveView模块是否已实施以处理jsEventToPhx您从前端发送的事件?您必须有一个父级LiveViewLiveViewComponent实现handle_event/3此消息的回调。看:

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客户端发送一些东西,那么这个过程会略有不同。push_event从任何回调返回套接字时使用的 LiveView handle_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);
  }
}

在此处检查客户端-服务器通信部分可能很有用。


推荐阅读