使用哈希标签
那么你有一个轻笑了我。
我有这个人在我的Helpers.elm
文件中,我可以用它来代替Html.Events.click
。
{-| Useful for overriding the default `<a>` behavior which
causes a refresh, but can be used anywhere
-}
overrideClick : a -> Attribute a
overrideClick =
Decode.succeed
>> onWithOptions "click"
{ stopPropagation = False
, preventDefault = True
}
所以上a [ overrideClick (NavigateTo "/route"), href "/route" ] [ text "link" ]
这将使中单击元素以及使用按压状态更新导航。
您需要的是与pushState一起使用的JavaScript类似的东西,而且您不想毁掉中间点击体验。您可以劫持其所有事件中的所有<a>
s,preventDefault
以停止浏览器导航,并通过目标的href推入新状态。您可以将导航的<a>
s委托给事件处理程序。由于Navigation
运行时不支持在外部监听历史记录更改(而似乎是使用效果管理器),所以必须将该值通过端口推送 - 幸运的是,如果您使用的是Navigation
包,则应该已经有件。
在Elm端,使用UrlParser.parsePath
与Navigation
programs之一结合使用。创建一个端口以订阅使用与其内部URL更改相同的消息。
import Navigation exposing (Location)
port externalPush : (Location -> msg) -> Sub msg
type Msg
= UrlChange Location
| ...
main =
Navigation.program UrlChange
{ ...
, subscriptions : \_ -> externalPush UrlChange
}
页面加载后,使用此:
const hijackNavClick = (event) => {
// polyfill `matches` if needed
if (event.target.matches("a[href]")) {
// prevent the browser navigation
event.preventDefault()
// push the new url
window.history.pushState({}, "", event.target.href)
// send the new location into the Elm runtime via port
// assuming `app` is the name of `Elm.Main.embed` or
// whatever
app.ports.externalPush.send(window.location)
}
}
// your nav selector here
const nav = document.querySelector("nav")
nav.addEventListener("click", hijackNavClick, false)
我认为这是可行的事件监听到你的锚链接连接到的preventDefault并通过端口来传递的意图,榆树 –
@SimonH似乎是这样,我正在考虑这个选择。如果可能的话,我想看看如何留在Elm。 – scoots