简体   繁体   English

如何在 Liveview 模板中停止页面刷新

[英]How to stop page refresh in a Liveview template

My LiveView app sets some initial states (eg, button_label) in the mount function.我的 LiveView 应用程序在mount函数中设置了一些初始状态(例如,button_label)。 The template appears to be re-mounted as it goes through some message passing.模板在通过一些消息传递时似乎被重新安装。

In the following example, the button label is initially set to "Click to run", and when the button is clicked, it successfully changes to "Running..." and then "Still in progrss".在下面的示例中,按钮标签最初设置为“单击以运行”,当单击按钮时,它成功更改为“正在运行...”,然后是“仍在进行中”。 However, mount is automatically run again, and the label goes back to "Click to run".但是, mount会再次自动运行,并且标签返回“单击以运行”。 The desired behavior is that the label stays as "Still in progress" until another message is received indicating the process is completed later in the process.所需的行为是标签保持为“仍在进行中”,直到收到另一条消息,指示该过程稍后完成。

What triggers the re-mounting, and how can I stop that?是什么触发了重新安装,我该如何阻止?

def mount(_params, _session, socket) do
   {:ok, assign(socket, button_label: "Click to run")}

def handle_event("run_process", value, socket) do
    live_view = self()

    Task.start(fn ->
      result = "Some tasks to run here"  
      send(live_view, {:in_progress, result})
    end)

    {:noreply, assign(socket, button_label: "Running..")}

def handle_info({:in_progress, result}, socket) do
    IO.inspect("result", label: "in_progress ++")
    {:noreply, assign(socket, button_label: "Still in progress")}
end


[Leex]
<button phx-click="run_process"><%= @button_label %> </button>

@schrockwell at the Elixir slack channel kindly provided this answer. Elixir slack 频道的@schrockwell 提供了这个答案。 It solved my problem.它解决了我的问题。

Try adding the type="button" attribute to the tag尝试将 type="button" 属性添加到标签

That will prevent the form from trying to be submitted on the button click.这将阻止表单尝试在按钮单击时提交。

[Leex]
<button type="button" phx-click="run_process"><%= @button_label %> </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM