vue-property-decorator 依赖 vue-class-component 实现,主要用了内部提供的 createDecorator 方法。
如果你想增加更多装饰器,也可以通过调用 createDecorator 方法,原理很简单,就是向选项对象上增加所需数据。
执行 createDecorator 添加的装饰函数
在 vue-class-component 中提供了工具函数 createDecorator 允许添加其他额外的装饰函数,统一挂载在 Component.decorators 上,并把 options 传过去,对 options 增加需要的属性,实际上会调用这些装饰函数,让这些函数有机会处理 options。
"Vue-Class-Component"提供了createDecorator方法来创建自定义的装饰器
createDecorator期望一个回调函数作为第一参数,这个回调函数将收到以下参数:
- options —— Vue组件选项对象,此对象的更改将影响所提供的组件
- key —— 应用装饰器的属性或方法
- parameterIndex —— 参数索引
decorators.ts
import { createDecorator } from "vue-class-component";
export const Log = createDecorator((options: any, key) => {
const originalMethod = options.methods[key];
options.methods[key] = function wrapperMethod(...args: []) {
console.log(`调用: ${key}(`, ...args, ")");
originalMethod.apply(this, args);
};
});
使用方法装饰器
<template>
<div class="about">
<h1>This is an about page</h1>
<button @click="hello">Hello</button>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Log } from "./decorators";
@Component
export default class About extends Vue {
mounted() {
this.hello("这是一个log");
}
@Log
hello(value: any) {
console.log('hello', value);
}
}
</script>