简体   繁体   English

如何仅将模型 [0] 从 Ember 中的模板传递给组件?

[英]How to pass only model[0] to a component from the template in Ember?

I want to pass only the model[0] (first data element) to a component from the template.我只想将模型 [0](第一个数据元素)传递给模板中的组件。 I have a route file as follows:我有一个路由文件如下:

/order.js
export default Route.extend({

  firstIndex: computed('data', {
    get(){
    return Ember.get(this,'data[0]');
    }
  }),

  model(params) {
    return fetch(`/api/salesrowmodel/${params.order_id}`)
    .then(resp => resp.json())
    .then(function(data) {
      return {
        data,
      };
    });
  },
}); 

FirstIndex is a computed property to return first index data of the array. FirstIndex 是一个计算属性,用于返回数组的第一个索引数据。 Now in the template, I want to pass the first index data to a component:现在在模板中,我想将第一个索引数据传递给一个组件:

/order.hbs

<div class="Revenue-values">{{order-detail data=firstIndex.revenueHeader}}</div>

My sample model data is as follows:我的示例模型数据如下:

[{
"OrderId": "406-5309498-5972326",
"revenueHeader": {
"Principal": 982.14,
"Product Tax": 117.86,
"Total": 1100
}},
{
"OrderId": "506-5234568-5934567",
"revenueHeader": {
"Principal": 382.54,
"Product Tax": 34.46,
"Total": 234
}}]

It shows the null or undefined object is being passed to order-details.它显示 null 或 undefined 对象正在传递给订单详细信息。 Please help me with this error.请帮我解决这个错误。

First of all, the template is not bound to the route but to the controller.首先,模板没有绑定到路由,而是绑定到控制器。 So you would need to move your computed property to the controller.所以你需要将你的计算属性移动到控制器。

Next Ember.get(this,'data[0]'); Next Ember.get(this,'data[0]'); is invalid.是无效的。 you can not use Ember.get to access a numeric property, and so an array element.您不能使用Ember.get访问数字属性,以及数组元素。 The dependency key computed('data', should also probably be computed('data.[]', .依赖键computed('data',也应该computed('data.[]',

However there is a far simpler approach:然而,有一个更简单的方法:

{{order-detail data=model.firstObject}}

because ember adds firstObject and lastObject to arrays.因为 ember 将firstObjectlastObject添加到数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM