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

Mis*_*hko 11 elm

在我的Elm程序中,我想基于查询字符串初始化我的模型.

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

initialModel =
  { width = 3
  , height = 5
  }
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*Cho 8

以下示例使用evancz/url-parserelm-lang/navigation为elm 0.18.对于榆木0.19,概念是相同的,因为这两个包都被移动并重新标记为官方elm/urlelm/browser库.

在文档中有一些不太直接的问题,但我在下面简要解释了它们.这个例子应该说明一切.

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) ]
        ]
Run Code Online (Sandbox Code Playgroud)

"技巧"是创建另一个类型别名,将查询参数放在其中.在上面的例子中,我创建了类型SearchParams.创建该类型后,我们只需使用一个initialModel它接受的currentPath.

从那里,我们的模型可以提取查询参数Maybe.withDefault(它需要是一个Maybe类型,因为参数可能不在那里).一旦我们在模型中获得了数据,我们就可以在视图中将其打印出来.

希望这可以帮助!


Apa*_*hka 7

没有内置的核心库方法来访问URL.您可以使用端口和社区库jessitron/elm-param-parsing.

如果您还想设置URL,您可以再次使用端口,或者您可以使用历史API,在TheSeamau5/elm-history中有绑定.