【问题标题】:Can't get value of array inside computed property无法在计算属性中获取数组的值
【发布时间】:2017-08-25 22:06:25
【问题描述】:

我在使用 Ember 中的计算属性时遇到问题。

有问题的项目是timeZones,设置如下:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      account: this.store.findRecord('account', params.id),
      timeZones: this.store.findAll('time-zone'), <------------ timeZones
      users: this.store.query('user', { by_account_id: params.id })
    });
  },

  setupController(controller, model) {
    this._super(controller, model.account);
    controller.set('users', model.users);
    controller.set('timeZones', model.timeZones);
  }
});

然后我有一个名为 selectedTimeZone 的东西,看起来像这样:

  selectedTimeZone: Ember.computed('location.timezone', 'timeZones', function() {
    console.log(this.get('timeZones'));

    const timeZoneName = this.get('location.timezone');
    var result;

    this.get('timeZones').forEach(function(timeZone) {
      if (timeZone.name === timeZoneName) {
        console.log('yes'); // <------------------- never gets here
        result = timeZone;
      }
    });

    return result;
  }),

问题是this.get('timeZones') 在组件内部是不可访问的。 timeZones 使它成为模板就好了。我现在用timeZones 填充下拉列表。但是当我console.log 它时,它只是以Class 的形式出现。

我怎样才能在这个计算属性中获得timeZones

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    实际上大部分看起来不错,但是缺少一些代码。这是组件还是控制器,如果是组件,如何调用组件?

    然而,一个问题是显而易见的。 timeZone 显然是 ember-data 记录,因此访问 timeZone.name 不是一个好主意。您应该使用 embers .get()timeZone.get('name')Ember.get(timeZone, 'name')

    接下来你的依赖键是错误的。因为您使用每个 timeZonename,所以您应该将依赖项键 timeZone 替换为 timeZone.@each.name

    最后一点使用findBy的CP的小版本:

    selectedTimeZone: Ember.computed('location.timezone', 'timeZones.@each.name', function() {
      const timeZoneName = this.get('location.timezone');
      return this.get('timeZones').findBy('name', timeZoneName);
    }),
    

    如果这不起作用,您应该使用 ember 检查器验证数据是否已成功加载到存储中,并在调用来自您的控制器的组件。

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 1970-01-01
      • 2020-11-26
      • 2019-06-25
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多