路由器改用 replaceState 更新 URL

您可以使用 replaceState 转换来阻止将项目添加到浏览器历史记录中。您可以通过在路由上使用 queryParams 配置哈希来指定这一点,并通过将 replace 转换设置为 true 来选择 replaceState 转换。

Syntax

Ember.Route.extend ({
   queryParams: {
      queryParameterName: {
         replace: true
      }
   }
});

示例

下面给出的示例展示了如何使用 replaceState 转换更新 URL。创建一个新路由并将其命名为 paramreplaceState,然后打开 router.js 文件以定义 URL 映射 −

import Ember from 'ember';
//以变量 Ember 的形式访问 Ember.js 库
import config from './config/environment';
//它以变量 config 的形式提供对应用程序配置数据的访问

//const 声明只读变量
const Router = Ember.Router.extend ({
    location: config.locationType,
    rootURL: config.rootURL
});

//定义以参数为对象来创建路由的 URL 映射
Router.map(function() {
   this.route('paramreplaceState');
});

//它指定可供应用程序其他部分使用的路由器变量
export default Router;

使用以下代码打开在 app/templates/ 下创建的 application.hbs 文件 −

<h2>Update URL with replaceState</h2>
{{#link-to 'paramreplaceState'}}Click Here{{/link-to}}

单击上述链接后,页面应打开,并显示一个按钮,单击后可更改 URL。使用以下代码打开 paramreplaceState.hbs 文件 −

//将操作发送到 addQuery 方法
<button {{action 'change'}}>Replace State</button>
{{outlet}}

现在打开在 app/controllers/ 下创建的 paramreplaceState.js 文件,该文件在进入路由时由路由器呈现 −

import Ember from 'ember';
var words = "tutorialspoint";

export default Ember.Controller.extend ({
   queryParams: ['query'],
   actions: {
      change: function() {

         //将变量"words"的值分配给"query",即查询参数
         this.set('query', words);
      }
   }
});

现在在 Route 上使用 queryParams 配置与相应的控制器,并在 app/routes/ 下创建的 paramreplaceState.js 文件中将 replace 配置属性设置为 true。

import Ember from 'ember';

export default Ember.Route.extend ({
   queryParams: {
      query: {
         // 将替换状态指定为 true
         replace: true
      }
   }
});

输出

运行 ember 服务器,您将收到以下输出 −

Ember.js Router Update URL replaceState

单击链接时,会显示向 addQuery 方法发送操作的按钮 −

Ember.js Router Update URL replaceState

单击按钮后,会在 URL 中"?"右侧显示参数值 −

Ember.js Router Update URL replaceState

emberjs_router.html