首页 > 语言 > JavaScript > 正文

Vue框架TypeScript装饰器使用指南小结

2024-05-06 15:42:19
字体:
来源:转载
供稿:网友

前言

装饰器是一种特殊类型的声明,它能够被附加到 类声明,方法, 访问符,属性或参数 上。 装饰器使用 @expression这种形式, expression求值 后必须为一个函数,它会在 运行时被调用 ,被装饰的声明信息做为参数传入。

本篇先从项目的宏观角度来总结一下Decorator如何组织。

目录

主要的Decorator依赖 vue-class-component vuex-class vue-property-decorator core-decorators 自定义Decorator示例 哪些功能适合用Decorator实现 Decorator实现小Tips See also

主要的Decorator依赖

vue-cli3 默认支持Decorator, 年初重写了一个design库主要依赖官方和社区提供的Decorator来实现的组件。 Decorator可以非侵入的装饰类、方法、属性,解耦业务逻辑和辅助功能逻辑。以下是主要的三方Decorator组件:

vue-class-component

@Component 如果您在声明组件时更喜欢基于类的 API,则可以使用官方维护的 vue-class-component 装饰器 实时计算computed属性, get computedMsg () {return 'computed ' + this.msg} 生命周期钩子 mounted () {this.greet()}

vuex-class

让Vuex和Vue之间的绑定更清晰和可拓展

@State @Getter @Action @Mutation

vue-property-decorator

这个组件完全依赖于vue-class-component.它具备以下几个属性:

@Component (完全继承于vue-class-component) @Prop:父子组件之间值的传递 @Emit:子组件向父组件传递 @Model:双向绑定 @Watch:观察的表达式变动 @Provice:在组件嵌套层级过深时。父组件不便于向子组件传递数据。就把数据通过Provide传递下去。 @Inject:然后子组件通过Inject来获取 Mixins (在vue-class-component中定义);

core-decorators

@readonly @autobind : TSX 回调函数中的 this,类的方法默认是不会绑定 this 的,可以使用autobind装饰器 @override

总结一下主要就分成这三类:

修饰类的:@Component、@autobind; 修饰方法的:@Emit、@Watch、@readonly、@override; 修饰属性的:@Prop、@readonly;

以上引用方法等详系内容可查看官方文档。下面自定义部分来实现一个记录日志功能的装饰器。

自定义Decorator示例

@Logger,Logger日志装饰器通常是修饰方法,Decorater则是在 运行时就被触发了 ,日志记录是在 方法被调用时触发 ,示例中通过自动发布事件实现调用时触发。为增加日志记录的灵活性,需要通过暴露钩子函数的方式来改变日志记录的内容。
期望的日志格式

{  "logId":"", // 事件Id  "input":"", // 方法输入的内容  "output":"", // 方法输出的内容  "custom":"" // 自定义的日志内容}

实现

export function Logger(logId?: string, hander?: Function) {  const loggerInfo =Object.seal({logId:logId, input:'',output:'', custom: ''});  const channelName = '__logger';  const msgChannel = postal.channel(channelName);  msgChannel.subscribe(logId, logData => {    // 根据业务逻辑来处理日志    console.log(logData);  });  return function (target: any,    key: string,    descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> {      const oldValue = descriptor.value      descriptor.value = function () {        const args: Array<any> = [];        for (let index in arguments) {        args.push(arguments[index]);        }        loggerInfo.input = `${key}(${args.join(',')})`;        // 执行原方法        const value = oldValue.apply(this, arguments);        loggerInfo.output = value;        hander && (loggerInfo.custom = hander(loggerInfo.input, loggerInfo.output) || '');        // 被调用时,会自动发出一个事件        msgChannel.publish(logId, loggerInfo);      }      return descriptor  }}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选