呈现的组件如下所示:
我期望的是,当我单击“添加对象”按钮时,它将创建一个新的Rental
记录,并将该Rental
记录追加到现有的RecordArray
上。由于已跟踪RecordArray
,因此将重新渲染组件模板,因此新记录的title
属性将显示在模板中。
当我单击按钮时,它将在Web检查器中返回此错误:
未捕获的TypeError:this.myrentals.pushObject不是MyCompComponent.addRental的函数
对于此问题中引用的应用程序的基本设置,我使用的是Ember Guides Tutorial App。
这是我的router.js
// router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function() {
this.route('testing');
});
这是我的路线,它返回RecordArray
条记录中的rental
条记录:
// testing.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class IndexRoute extends Route {
@service store;
model() {
return this.store.findAll('rental');
}
}
这是我的rental
模型:
// rental.js
import Model, { attr } from '@ember-data/model';
export default class RentalModel extends Model {
@attr title;
}
我的testing
模板:
//templates/testing.hbs
<MyComp @rentals={{@model}} />
我的MyComp
组件模板:
// components/my-comp.hbs
<h2>Practice Iterate over RecordArray and Add items</h2>
<ul>
{{#each @rentals as |rental| }}
<li>{{rental.title}}</li>
{{/each}}
</ul>
<button type="button" {{on "click" this.addRental}}>Add an object</button>
最后,我随附的MyComp
组件类:
// components/my-comp.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { A } from '@ember/array';
export default class MyCompComponent extends Component {
@tracked myRentals = this.args;
@action
addRental() {
this.myRentals.pushObject({
title: "My new rental"
});
}
}
我确实引用了Ember JS Looping Through Lists Guide。我显然在这里缺少一个或多个概念。
谢谢!
答案 0 :(得分:1)
我知道了!
这是组件模板:
//components/my-comp.hbs
<h2>Practice Iterate over RecordArray and Add items</h2>
<ul>
{{#each this.myRentals as |rental| }}
<li>{{rental.title}}</li>
{{/each}}
</ul>
<button type="button" {{on "click" this.addRental}}>Add an object</button>
这是组件的类:
// components/my-comp.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
export default class MyCompComponent extends Component {
@service store;
@tracked myRentals = this.args.rentals;
@action
addRental() {
this.myRentals.pushObject(this.store.createRecord('rental', {title: "test"}));
}
}
我需要纠正一些细节:
store
,然后将其设置为属性。rentals
模板中的my-comp
变量,我需要由this.args.rentals
对其进行捕获。RecordArray
记录的Rental
中,我不得不用rental
实例化this.store.createRecord
记录。我希望这对其他人有帮助!