gpt4 book ai didi

elm - 如何在 Elm 中获取查询参数?

转载 作者:行者123 更新时间:2023-12-04 01:51:07 24 4
gpt4 key购买 nike

在我的 Elm 程序中,我想根据查询字符串初始化我的模型。

例如,如果查询字符串是 ?w=3&h=5我想要:

initialModel =
{ width = 3
, height = 5
}

是否有可能在 Elm 中实现这一点,或者唯一的方法是在 Javascript 中获取查询参数并通过端口传递它们?

最佳答案

榆树 0.19

对于 elm 0.19,以下概念是相同的。这两个包仍然存在,但已被移动并重新标记为官方 elm/url elm/browser 图书馆。

榆树 0.18

此示例使用 evancz/url-parser elm-lang/navigation .文档中有一些问题并不简单,但我在下面简要解释了它们。这个例子应该说明一切。

module Main exposing (..)

import Html as H exposing (..)
import Navigation exposing (Location)
import UrlParser as UP exposing ((</>), (<?>), top, parsePath, oneOf, s, stringParam, Parser)
import Maybe.Extra as MaybeExtra exposing (unwrap)


type Route
= UrlRoute (Maybe String) (Maybe String)
| NotFoundRoute


type Msg
= UrlParser Navigation.Location


type alias Model =
{ location : Route
, w : String
, h : String
}


type alias SearchParams =
{ w : Maybe String, h : Maybe String }


main =
Navigation.program UrlParser
{ init = init
, view = view
, update = update
, subscriptions = (\_ -> Sub.none)
}


init : Location -> ( Model, Cmd Msg )
init location =
let
currentPath =
parseLocation location
in
( initialModel currentPath
, Cmd.none
)


parseLocation : Location -> Route
parseLocation location =
case (parsePath matchers location) of
Just route ->
route

Nothing ->
NotFoundRoute


matchers : Parser (Route -> a) a
matchers =
UP.map UrlRoute (UP.s "index" <?> UP.stringParam "w" <?> UP.stringParam "h")


initialModel : Route -> Model
initialModel route =
{ location = route
, w = MaybeExtra.unwrap "" (\x -> Maybe.withDefault "" x.w) (parseParams route)
, h = MaybeExtra.unwrap "" (\x -> Maybe.withDefault "" x.h) (parseParams route)
}


parseParams : Route -> Maybe SearchParams
parseParams route =
case route of
UrlRoute w h ->
Just { w = w, h = h }

NotFoundRoute ->
Nothing


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UrlParser location ->
( model
, Cmd.none
)


view : Model -> Html msg
view model =
div []
[ h1 [] [ text "URL Info" ]
, div [] [ text ("W is: " ++ model.w) ]
, div [] [ text ("H is: " ++ model.h) ]
]

“技巧”是创建另一个类型别名来放置您的查询参数。在上面的例子中,我创建了 SearchParams 类型。 .创建此类型后,我们只需使用 initialModel接受 currentPath .

从那里,我们的模型可以使用 Maybe.withDefault 提取查询参数。 (它必须是 Maybe 类型,因为参数可能不存在)。一旦我们将数据放入模型中,我们只需将其打印到 View 中即可。

希望这可以帮助!

关于elm - 如何在 Elm 中获取查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com