榆木中的本地存储或其他数据持久性

问题描述 投票:11回答:3

我才刚开始用Elm来构建一个简单的Web应用程序的想法。我的想法是需要在浏览器中保留一些用户数据。

是否有一种方法可以直接使用Elm处理数据持久性?例如在浏览器会话中,甚至在本地存储中?还是应该使用端口将其用于JavaScript?

elm
3个回答
3
投票

您可以看一下TheSeamau5's elm-storage。这样就可以将数据存储在本地存储中。


13
投票

我建议使用localStorage。最新的Elm(目前为0.17)没有官方支持,但您可以通过端口轻松实现。这是一个工作示例(基于官方文档的示例),该示例通过elm 0.17的端口使用localStorage

port module Main exposing (..)

import Html exposing (Html, button, div, text, br)
import Html.App as App
import Html.Events exposing (onClick)
import String exposing (toInt)

main : Program Never
main = App.program
  {
    init = init
  , view = view
  , update = update
  , subscriptions = subscriptions
  }

type alias Model = Int

init : (Model, Cmd Msg)
init = (0, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions model = load Load

type Msg = Increment | Decrement | Save | Doload | Load String

port save : String -> Cmd msg
port load : (String -> msg) -> Sub msg
port doload : () -> Cmd msg

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
      Increment ->
        ( model + 1, Cmd.none )
      Decrement ->
        ( model - 1, Cmd.none )
      Save ->
        ( model, save (toString model) )
      Doload ->
        ( model, doload () )
Load value ->
        case toInt value of
          Err msg ->
            ( 0, Cmd.none )
          Ok val ->
            ( val, Cmd.none )

view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick Increment ] [ text "+" ]
    , br [] []
    , button [ onClick Save ] [ text "save" ]
    , br [] []
    , button [ onClick Doload ] [ text "load" ]
    ]

和index.html

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <script type="text/javascript" src="js/elm.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
    var storageKey = "token";
    var app = Elm.Main.fullscreen();
    app.ports.save.subscribe(function(value) {
      localStorage.setItem(storageKey, value);
    });
    app.ports.doload.subscribe(function() {
      app.ports.load.send(localStorage.getItem(storageKey));
    });
</script>
</html>

现在,通过按+/-键,您可以更改int值。当您按下“保存”按钮时,该应用会将实际值存储到localStorage中(通过“令牌”键)。然后尝试刷新页面,然后按“加载”按钮-它从localStorage中取回值(您应该会看到使用恢复后的值实现的HTML文本控件)。


4
投票

官方的答案是在等待Elm官方本地存储库的重新发布:“ https://github.com/elm-lang/persistent-cache时使用”使用端口“(对于0.18-0.19.1)>

© www.soinside.com 2019 - 2024. All rights reserved.