ELM - 消息
创建于 2024-12-03 /
21
字体:
[默认]
[大]
[更大]
消息是Elm架构中的一个组件。 这些组件由视图生成,以响应用户与应用程序界面的交互。 消息代表用户更改应用程序状态的请求。
语法
--Message Syntax type Message = some_message1 |some_message2 ...|some_messageN
示例
以下示例是一个简单的计数器应用程序。 当用户分别单击"添加"和"减去"按钮时,应用程序会将变量的值递增和递减 1。
该应用程序将有 4 个组件。 各组件描述如下 −
Message
此示例的消息将是 −
type Message = Add | Subtract
Model
模型代表应用程序的状态。 在计数器应用中,模型定义如下; 计数器的初始状态为零。
model = 0
View
视图代表应用程序的视觉元素。 该视图包含两个按钮 (+) 和 (-)。 当用户分别单击 + 和 - 按钮时,视图会生成消息"添加"和"减去"。 然后模型的修改值由视图显示。
view model = -- invoke text function h1[] [ div[] [text "CounterApp from TutorialsPoint" ] ,button[onClick Subtract] [text "-"] ,div[][text (toString model)] ,button[onClick Add] [text "+"] ]
Update
该组件包含应该为视图生成的每条消息执行的代码。 如下例所示 −
update msg model = case msg of Add -> model+1 Subtract -> model-1
Putting it all together
步骤 1 − 创建文件夹
步骤 2 − 在elm文件中添加以下代码 −
import Html exposing (..) import Html.Events exposing(onClick) model = 0 -- Defining the Model --Defining the View view model = h1[] [ div[] [text "CounterApp from TutorialsPoint" ] ,button[onClick Subtract] [text "-"] ,div[][text (toString model)] ,button[onClick Add] [text "+"] ] --Defining the Messages type Message = Add | Subtract --Defining Update update msg model = case msg of Add -> model+1 Subtract -> model-1 -- Define the main method main = beginnerProgram { model=model ,view=view ,update=update }
步骤 3 − 在终端中执行 elm make 命令。 elm make 命令编译代码并从上面创建的 .elm 文件生成 HTML 文件。
C:UsersdellelmMessagesApp> elm make .MessageDemo.elm Some new packages are needed. Here is the upgrade plan. Install: elm-lang/core 5.1.1 elm-lang/html 2.0.0 elm-lang/virtual-dom 2.0.4 Do you approve of this plan? [Y/n] y Starting downloads... elm-lang/html 2.0.0 elm-lang/virtual-dom 2.0.4 elm-lang/core 5.1.1 Packages configured successfully! Success! Compiled 38 modules. Successfully generated index.html
步骤 4 − 打开 index.html 并验证工作正常,如下所示 −

0 人点赞过