没有散​​列或正则表达式的替代单页应用程序路由机制

Alternative Single Page Application routing mechanism without hash or regex

我正在开发自己的 SPA(单页应用程序)堆栈工具。我目前正在考虑路由器机制——我怀疑我是否应该使用基于哈希 (#) 的路由器,或者考虑其他事情:

  1. 使用 window.history API - twitter 已经做了一些小的 SPA 助手:为 twitter.com (https://blog.twitter.com/2012/implementing-pushstate-for-twittercom) 实现 pushState - 不是真的知道为什么其他流行的(React,Angular)框架路由器不使用它而依赖哈希机制吗?

  2. 使用哈希实现,但为了提高url映射速度(和实现)只使用一层嵌套路由+参数,例如:

    • #/posts,
    • #/post-new/,
    • #/post/<post-id>,
    • #/post-edit/<post-id>,
    • #/post-comments/<post-id>

所以没有复杂的正则表达式,在第一个斜杠之后总是只有一个非常具有描述性的路由 slug,在第二个斜杠之后将是一个参数(或 ?param1=X&param2=Y 等参数)。这种(第二点)方法有什么缺陷吗?

编辑:

由于重复回答 - 不,我不想使用现有的解决方案(angular/react/ember 等) - 我想自己实现它(我想为自己构建工具,而不是挣扎现有 API 不适合我)

简答

良好前端路由的唯一两种可能性是使用 history api 或默认哈希实现。

长答案

您可以使用 AngularJS and remove the # from the URLs telling to angular to use the history api (tutorial):

angular.module('test', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

  }]);

也许您需要 <head>:

<base href="/">

使用 $locationProvider.html5Mode(true); 你实际上告诉 angular 使用历史记录 api。

"Don’t really know why other popular (React, Angular) framework routers don’t use it and rely on hash mechanism?" 因为IE9及之前版本不支持历史api 可以看到here.

angular 应用程序的一个示例是 Google Font

,其中没有 #,因此启用了 html5Mode