Ember.js dasherize()方法
Ember.js是一个开源的JavaScript框架,用于开发基于模型-视图-控制器(MVC)架构的大型客户端Web应用程序。Ember.js是最广泛使用的前端应用程序框架之一,因为它旨在加快开发速度并提高生产力。目前,它被许多网站使用,包括Square, Discourse, Groupon, Linked In, Live Nation, Twitch和Chipotle。
dasherize()方法用于生成给定字符串的破折号版本。
语法:
dasherize(str)
参数:
- str(string): 要转换为破折号的字符串。
返回值: 转换为破折号的字符串。
创建应用程序: 要运行以下示例,您需要一个ember项目。要创建一个项目,您需要先安装ember-cli。然后在终端中输入下面的代码:
npm install ember-cli
现在您可以通过键入以下代码片段来创建项目:
ember new <project-name> --lang en
要启动服务器,请键入:
ember serve
示例1
输入以下代码以生成此示例的路线:
ember generate route richest-people
app/routes/richest-people.js
import Route from '@ember/routing/route';
import { dasherize } from '@ember/string';
export default class RichestPeopleRoute extends Route {
richestPeople = [
'elon Musk',
'bernard Arnault and family',
'jeff Bezos',
'Bill gates',
'gautam adani and family',
'Larry Page',
'Warren Buffet',
'larryEllison',
'mukesh ambani',
'sergeyBrin',
];
model() {
return this.richestPeople.map(dasherize);
}
}
app/template/richest-people.hbs
{{page-title "Richest People"}}
<h2>Top 10 Richest People in the World</h2>
<ul>
{{#each @model as |rich-person|}}
<li>{{rich-person}}</li>
{{/each}}
</ul>
{{outlet}}
输出: 访问 localhost:4200/richest-people 查看输出
示例2
输入以下代码以生成此示例的路由:
ember generate route languages
app/routes/languages.js
import Route from '@ember/routing/route';
import { dasherize } from '@ember/string';
export default class LanguagesRoute extends Route {
name = ['mandarin Chinese', 'spanish', 'english',
'Hindi', 'bengali', 'Portuguese', 'russian',
'japanese', 'western_punjabi', 'yueChinese'];
num = [929.0, 474.7, 372.9, 343.9, 233.7, 232.4,
154.0, 125.3, 92.7, 85.2];
languages = [];
initLanguages() {
this.languages = [];
for(let i = 0; i<this.name.length; i++) {
let obj = new Object();
obj['name'] = dasherize(this.name[i]);
obj['num'] = this.num[i];
this.languages.push(obj);
}
}
model() {
this.initLanguages();
return this.languages;
}
}
app/template/languages.hbs
{{page-title "Languages"}}
<h2>Most Spoken Languages in the World</h2>
<table style="border: 2px solid black;padding: 30px;">
<tr>
<th>Language</th>
<th>Native Speakers (millions)</th>
</tr>
{{#each @model as |language|}}
<tr>
<td>{{language.name}}</td>
<td>{{language.num}}</td>
</tr>
{{/each}}
</table>
{{outlet}}
输出: 访问 localhost:4200/languages 来查看输出结果
参考: https://api.emberjs.com/ember/release/classes/String