如何在Phoenix Framework中获取输入框的值?
问题:LiveView聊天功能无法将消息添加到聊天记录
我尝试从HTML输入框获取聊天消息文本,将其添加到下方的聊天记录中,但当前代码无法正常工作。以下是我的代码:
defmodule ChatWeb.ChatLive do use ChatWeb, :live_view def mount(params, session, socket) do {:ok, assign(socket, :text_value, "")} end def render(assigns) do ~H""" <h1>Chat</h1> <form phx-submit="submit"> <label>Your Text:<input id="msg" type="text" name="input_value" /></label> <button>Send</button> </form> <div id="chat"> Chat history: <%= @text_value %> </div> """ end def handle_event("send-msg", %{"input_value" => msg}, socket) do {:noreply, assign(socket, :text_value, msg)} end end
当前界面效果:

修复方案
当前代码存在两个核心问题:表单提交事件名与处理函数不匹配,以及聊天历史仅能存储单条消息。以下是修复后的代码及说明:
修复后的完整代码
defmodule ChatWeb.ChatLive do use ChatWeb, :live_view def mount(params, session, socket) do # 初始化聊天历史为空列表 {:ok, assign(socket, :chat_history, [])} end def render(assigns) do ~H""" <h1>Chat</h1> <!-- 统一表单提交事件名为send-msg,与handle_event监听的事件匹配 --> <form phx-submit="send-msg"> <label>Your Text:<input id="msg" type="text" name="input_value" /></label> <button>Send</button> </form> <div id="chat"> Chat history: <!-- 遍历聊天历史列表,渲染每条消息 --> <%= for msg <- @chat_history do %> <div><%= msg %></div> <% end %> </div> """ end def handle_event("send-msg", %{"input_value" => msg}, socket) do # 将新消息追加到聊天历史列表头部(若需按时间正序显示,可改为socket.assigns.chat_history ++ [msg]) updated_history = [msg | socket.assigns.chat_history] {:noreply, assign(socket, :chat_history, updated_history)} end end
关键修复点
- 事件名匹配:将表单的
phx-submit属性值从"submit"改为"send-msg",确保提交时能触发对应的handle_event处理函数 - 存储聊天历史:用列表
chat_history替代单个字符串text_value,实现多条消息的累积存储 - 渲染多条消息:使用EEx循环遍历聊天历史列表,逐条渲染消息,展示完整的聊天记录
内容的提问来源于stack exchange,提问作者Athshe
相关产品推荐
相关产品推荐

