【Angular中的Decorator】- 属性装饰器 (Property decorators)

        属性装饰器顾名思义,用来装饰类的属性。它接收两个参数:

        target :被装饰的属性所属类的对象

        key : 被装饰的属性名

1、不带参数的属性装饰器

        以下示例演示通过属性装饰器跟踪属性的修改:

function changeLog(target: any, key: string) {
    var _value: string = target[key];
    if(delete target[key]) {
        Object.defineProperty(target, key, {
            get: function () {
                return _value;
            },
            set: function (value) {
                _value = value;
                console.log(`set ${key} = ${value}`);
            }
        });
    }
}
 
export class Grape {
    @changeLog
    price: number = 0;
    constructor(price: number) {
        this.price = price;
    }
}
 
//组件中调用代码
let grape = new Grape(4);
grape.price = 8;

        运行程序打印如下:

 2、带参数的属性装饰器

        当然,属性装饰器也可以传递参数,以下示例演示通过属性装饰器传递参数,对用户修改属性值进行限制,超过最大最小值将抛出异常:

function changeLog(config: { max?: number, min?: number }) {
    return function (target: any, key: string) {
        var _value: string = target[key];
        if (delete target[key]) {
            Object.defineProperty(target, key, {
                get: function () {
                    return _value;
                },
                set: function (value) {
                    if (config.max && value > config.max) {
                        throw `try to set price too high, max: ${config.max}, try: ${value}`;
                    }
                    if (config.min && value < config.min) {
                        throw `try to set price too low, min: ${config.min}, try: ${value}`;
                    }
                    _value = value;
                    console.log(`set ${key} = ${value}`);
                }
            });
        }
    }
}

export class Grape {
    @changeLog({ min: 6 })
    price: number = 6;
    
    constructor(price: number) {
        this.price = price;
    }
}

//组件中调用代码
let grape = new Grape(4);
grape.price = 8;

        运行程序打印如下:

         以上示例 price 属性装饰器设置了最小值 6,在组件中调用 new Grape(4),小于了最小值,所以抛出了设置异常信息。

         属性装饰器的使用就介绍到这里,欢迎意见交流。

猜你喜欢

转载自blog.csdn.net/evanyanglibo/article/details/122585679
今日推荐