繁体   English   中英

为什么 phoenix liveview 更新/分配消息使客户端 contenteditable 值恢复?

[英]why phoenix liveview update/assign message make client contenteditable value revert?

使用 Phoenix 实时视图文档,我添加了一个用于编写实时表单应用程序的实时页面。 有一个非常简单的演示:

<h2>Hello</h2>

Counter is222: <%= @counter %>
<hr>

<button phx-click="dec">-</button>
<button phx-click="inc">+</button>

<table border="1">
  <tr>
    <th contenteditable="true">Month</th>
    <th>S1</th>
    <th>S2</th>
  </tr>
  <tr>
    <td contenteditable="true">January</td>
    <td contenteditable="true">$100</td>
    <td contenteditable="true">$10220</td>
  </tr>
</table>

服务器端代码(就像文档一样):

defmodule TicTacWeb.MemberSchedulerLive do
  use Phoenix.LiveView


  def render(assigns) do
    TicTacWeb.PageView.render("member_scheduler.html", assigns)
  end

  def mount(_, socket) do
    {:ok, assign(socket, %{counter: 100})}
  end

  def handle_event("inc", _, socket) do
    {:noreply, update(socket, :counter, fn(x) -> x + 1 end)}
  end

  def handle_event("dec", _, socket) do
    IO.puts("item")
    {:noreply, update(socket, :counter, fn(x) -> x - 1 end)}
  end

end

问题是<td contenteditable值将在我单击后恢复-+向服务器发送消息。

  1. 为什么-+会影响<td>的值? 是不是最小化更改修改了 dom 数据?
  2. 这种场景有最佳实践吗?

谢谢!

更新
添加 contenteditable 作为数据模型后,还是不行,比如:
1. html 片段

    ....
    <td contenteditable="true">$100</td>
    <td contenteditable="true" phx-blur="somedata"><%=@somedata%></td>
  </tr>
</table>
  1. 后端
  ...
  def mount(_, socket) do
    {:ok, assign(socket, %{counter: 100, somedata: "$001"})}
  end

如果单击-+@somedata也会恢复为 $001。

为什么-+会影响<td>的值?

反之亦然。 它们不影响<td>的值,相反,它发送前一个状态和更新状态之间的差异,前端应用这个差异

LiveView不知道您使用contenteditable="true"所做的本地更改,因此它将所有内容重置为其原始状态,除了:counter会更新。 要支持contenteditable="true"您需要将这些<td>设为数据模型的一部分,以便LiveView了解其中的更改。

我终于通过两步解决了这个问题:

  1. 添加phx-update='ignore'并且 contenteditable 将不会更新!
    在这个阶段,它是<td contenteditable="true" phx-update='ignore'>$10220</td>

  2. 将 phoenix_live_view 更新为 0.4.1,即github: phoenixframework/phoenix_live_view (锁定提交为:73e9a695eff1d7d21e4cb34ea9894835b3a2fa32),旧版本似乎不支持phx-update

希望它也可以帮助你。

谢谢@Aleksei Matiushkin,我将深入研究实时视图差异算法。

暂无
暂无

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

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