当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

使用Replacestate更新URL(Update URL with Replacestate Instead)

优质
小牛编辑
126浏览
2023-12-01

您可以使用replaceState转换阻止将项添加到浏览器的历史记录中。 您可以通过在Route上使用queryParams配置哈希来指定它,并通过将replace transition设置为true来选择进入replaceState转换。

语法 (Syntax)

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

例子 (Example)

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

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 
//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});
//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('paramreplaceState');
});
//It specifies Router variable available to other parts of the app
export default Router;

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

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

当您单击上面的链接时,页面应该打开一个按钮,以便在单击后更改URL。 使用以下代码打开paramreplaceState.hbs文件 -

//sending action to the addQuery  method
<button {{action 'change'}}>Replace State</button>
{{outlet}}

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

import Ember from 'ember';
var words = "xnip";
export default Ember.Controller.extend ({
   queryParams: ['query'],
   actions: {
      change: function() {
         //assigning value of variable 'words' to the 'query' i.e. query parameter
         this.set('query', words);
      }
   }
});

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

import Ember from 'ember';
export default Ember.Route.extend ({
   queryParams: {
      query: {
         //assigning replace state as true
         replace: true
      }
   }
});

输出 (Output)

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

Ember.js路由器更新URL replaceState

当您单击该链接时,它会显示向addQuery方法发送操作的按钮 -

Ember.js路由器更新URL replaceState

单击按钮后,它将显示“?”右侧的参数值。 在URL中 -

Ember.js路由器更新URL replaceState