【问题标题】:window.location.assign() is not catched by Router in dartdart 中的路由器未捕获 window.location.assign()
【发布时间】:2015-06-06 04:42:55
【问题描述】:

我尝试使用来自route_hierarchical/client.dart 的路由器来监听 onpopstate 事件并在我的 index.html 中启用/禁用<div>。 (stagehand.pub dart 插件中的示例) 如果这是通过 index.html 中的普通<a href="/relativePath"> 完成的,它可以工作。 但是,如果我尝试通过我调用的button.onClick.listen() 处理程序更改路径:

window.location.assign('/relativePath');

我得到 404 并且路由器没有正确处理我的事件。 该操作是否应该不调用像here 描述的那样被路由器捕获的popstate event

handlers.dart

...
button.onClick.listen((_){
   window.location.assign('/about');
});

...

router.dart

var router = new Router();
  router.root
    ..addRoute(name: 'about', path: '/about', enter: showAbout)
    ..addRoute(name: 'login', defaultRoute: true, path: '/', enter: showLogin)
    ..addRoute(name: 'context', path: '/context', enter: showContext);
  router.listen();
}

void showAbout(RouteEvent e) {
  // Extremely simple and non-scalable way to show different views.
  querySelector('#login').style.display = 'none';
  querySelector('#about').style.display = '';
  querySelector('#context').style.display = 'none';
} ...

index.html

...
<form>
    <button type="button" id="submit" disabled="true" >
        Login
    </button>
</form>
...

【问题讨论】:

  • 看起来像一个错误,请在dartbug.com 报告)。你可以试试window.location.href = xxx(另见stackoverflow.com/questions/13109233
  • 感谢您的回复,我之前看过该帖子,但不幸的是 href setter 也不起作用:-(

标签: html dart dart-html


【解决方案1】:

好吧,假设上述行为似乎我没有实现我的目标。

感谢 Günther Zöchbauer 的帮助。 我将其提交给相应的Github project,因为我认为它应该可以工作。

我现在使用的以及包括历史支持在内的工作是

router.gotoUrl('/relativePath')

在 onButtonClick 处理程序中。 完全做到了。

【讨论】:

    【解决方案2】:

    onPopState 是错误事件。仅当您导航到现有历史条目(后退、前进、pushState、转到历史中的第二个条目)时才会触发此事件。 您正在寻找的可能是window.onHashChange 事件。

    【讨论】:

    • 看来我弄错了,但路由器不应该在内部处理吗?
    • 这取决于路由器配置(我也不是这方面的专家)。您可以启用 usePushState。根据此设置,您必须使用 URL 片段 (http://example.com/index.html#someroute) 或整个 URL 来表示在加载资源时需要服务器支持的路由(如 http://example.com/someroute)。你设置的 URL 需要根据这个方案匹配一个路由。
    猜你喜欢
    • 2015-03-16
    • 2016-10-21
    • 1970-01-01
    • 2021-03-26
    • 2017-04-03
    • 1970-01-01
    • 2022-11-24
    • 2023-01-04
    • 1970-01-01
    相关资源
    最近更新 更多