默认值和反序列化(Default Values and Deserialization)
优质
小牛编辑
140浏览
2023-12-01
您可以为控制器查询参数属性设置默认值,该属性的值不会序列化到URL中。
语法 (Syntax)
Ember.ArrayController.extend ({
queryParams: 'queryParameterName',
queryParameterName: defaultValue
});
例子 (Example)
下面给出的示例指定将默认值设置为查询参数。 创建一个新路由并将其命名为defaultvaluedeserialize并打开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('defaultvaluedeserialize');
});
//It specifies Router variable available to other parts of the app
export default Router;
使用以下代码打开在app/templates/下创建的application.hbs文件 -
<h2>Default Values and Deserialization</h2>
{{#link-to 'defaultvaluedeserialize'}}Click Here{{/link-to}}
单击上面的链接时,页面应打开一个输入框,该输入框取用户输入的值。 打开defaultvaluedeserialize.hbs文件并添加以下代码 -
//sending action to the addQuery method
<form {{action "addQuery" on = "submit"}}>
{{input value = queryParam}}
<input type = "submit" value = "Send Value"/>
</form>
{{outlet}}
现在打开在app/controllers/下创建的defaultvaluedeserialize.js文件,其中包含以下代码 -
import Ember from 'ember';
export default Ember.Controller.extend ({
//assigning query parameter name as 'query'
queryParams: 'query',
//assigning the query param to a default value as 1
query: 1,
queryParam: Ember.computed.oneWay('query'),
actions: {
addQuery: function () {
this.set('query', this.get('queryParam'));
document.write(this.get('query'));
}
}
});
输出 (Output)
运行ember服务器,您将收到以下输出 -

单击链接时,它会在输入框中显示指定的默认值 -

单击按钮后,它将显示默认值,并且不会序列化到URL中 -
