【问题标题】:EmberJS: Computed property awareness of dependent keysEmberJS:依赖键的计算属性意识
【发布时间】:2020-05-21 22:54:32
【问题描述】:

假设我有一个具有这种结构的对象: { filters: [{ params: { value: ["abc"] }] }.

如何编写一个知道value 属性更改的计算属性?例如,假设我们采用其中一个过滤器并执行set(filter, 'params.value', ["abc", "123"])。我一直在尝试使用computed('filters.@each.params.value.[]', ...),但它不起作用

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    好吧,我想我知道如何帮助你。首先,用deeply nested keys after@each 来计算属性似乎是不可能的。这就是为什么为了完成这项工作,必须将其拆分。像这样的:

    export default Component.extend({
      init() {
        this._super(...arguments);
    
        this.o = {filters: [{params: {value: ["abc"]}}]};
      },
    
      params: computed('o.filters.@each.params', function () {
        return this.o.filters.mapBy('params');
      }),
    
      paramsValue: computed('params.@each.value', function () {
        let aaa = this.params; // it seems like we need to reference the params anyhow
        return JSON.stringify(this.o);
      }),
    
      @action
      changeClassic() {
        let filter = this.o.filters[0];
        set(filter, 'params.value', ['abc', '123']);
      }
    
    });
    

    我还尝试在带有@tracked 的微光组件的情况下解决相同的问题。在那里我必须use a separate class 并跟踪value 字段:

    class ValueHandler {
      @tracked value;
    
      constructor(value) {
        this.value = value;
      }
    }
    
    export default class DeepObjectTestComponent extends Component {
    
      @tracked o = {filters: [{params: new ValueHandler('abc')}]};
    
      // so here I don't need an intermediate computed (hope this works for a more complicated  scenario
      get paramsValue() {
        let aaa = this.o.filters[0].params.value;
        return JSON.stringify(this.o);
      }
    
      @action
      changeGlimmer() {
        let filter = this.o.filters[0];
        // set(filter, 'params.value', ['abc', '123']);
        filter.params.value = ['abc', '123'];
      }
    }
    
    

    【讨论】:

    • 是的,我也这样做。您已经通过微光跟踪使您的课程变得平坦。要嵌套,您必须在类中创建一个类。感觉有点倒退,但我敢肯定有技术性能方面的原因。