Ember.js、set() 和计算属性

Ember.js, set(), and computed properties

我正在通读 set() 方法的 Ember.js API reference,但我不理解某一特定段落。

Computed Properties

If you try to set a value on a key that has a computed property handler defined (see the get() method for an example), then set() will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties.

我了解 set() 如何独立工作,但设置计算属性(函数)仍然没有点击,即使阅读了本段。

谁能给出额外的解释或例子?

您可以阅读 https://guides.emberjs.com/v2.14.0/object-model/computed-properties/#toc_setting-computed-properties 以获得更好的理解。

在这里我只是想解释同样的事情。

import Ember from 'ember';
export default Ember.Component.extend({
    firstName: '',
    lastName: '',
    fullNameCP: Ember.computed('firstName', 'lastName', function() {
        return `${this.get('firstName')} ${this.get('lastName')}`
    }),
    fullNameCPwithGetSet: Ember.computed('firstName', 'lastName', {
        get(key) {
            return `${this.get('firstName')} ${this.get('lastName')}`;
        },
        set(key, value) {
            let [firstName, lastName] = value.split(/\s+/);
            this.set('firstName', firstName);
            this.set('lastName', lastName);
            return value;
        }
    })
});

在上面,
如果我们说 this.set('fullNameCP','Yehuda Katz') 之后它将被视为正常 属性 它将不会被视为计算 属性。您不应手动将 fullNameCP 设置为新值。如果你想这样做,那么你需要定义 Computed 属性 with Getter and Setter like fullNameCPwithGetSet

如果我们说,this.set('fullNameCPwithGetSet','Yehuda Katz'),那么它也会通过传递值来调用计算 属性 fullNameCPwithGetSetset 方法,即 Yehuda Katz 所以我们可以为依赖键设置准确的值。