![](/img/trans.png)
[英]Passing a value from client to Phoenix server using LiveView during mount
[英]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
值將在我單擊后恢復-
或+
向服務器發送消息。
-
或+
會影響<td>
的值? 是不是最小化更改修改了 dom 數據?謝謝!
更新
添加 contenteditable 作為數據模型后,還是不行,比如:
1. html 片段
....
<td contenteditable="true">$100</td>
<td contenteditable="true" phx-blur="somedata"><%=@somedata%></td>
</tr>
</table>
...
def mount(_, socket) do
{:ok, assign(socket, %{counter: 100, somedata: "$001"})}
end
如果單擊-
或+
, @somedata
也會恢復為 $001。
為什么
-
或+
會影響<td>
的值?
反之亦然。 它們不影響<td>
的值,相反,它發送前一個狀態和更新狀態之間的差異,前端應用這個差異。
LiveView
不知道您使用contenteditable="true"
所做的本地更改,因此它將所有內容重置為其原始狀態,除了:counter
會更新。 要支持contenteditable="true"
您需要將這些<td>
設為數據模型的一部分,以便LiveView
了解其中的更改。
我終於通過兩步解決了這個問題:
添加phx-update='ignore'
並且 contenteditable 將不會更新!
在這個階段,它是<td contenteditable="true" phx-update='ignore'>$10220</td>
將 phoenix_live_view 更新為 0.4.1,即github: phoenixframework/phoenix_live_view
(鎖定提交為:73e9a695eff1d7d21e4cb34ea9894835b3a2fa32),舊版本似乎不支持phx-update
希望它也可以幫助你。
謝謝@Aleksei Matiushkin,我將深入研究實時視圖差異算法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.