Vue Class Component 自定义装饰器
Vue Class Component 自定义装饰器
Custom Decorators
你可以通过创建自己的装饰器(decorators)来扩展此库的功能。
"Vue-Class-Component"提供了createDecorator方法来创建自定义的装饰器
createDecorator期望一个回调函数作为第一参数,这个回调函数将收到以下参数:
- options —— Vue组件选项对象,此对象的更改将影响所提供的组件
- key —— 应用装饰器的属性或方法
- parameterIndex —— 参数索引
Example
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);
};
});
在About.vue使用方法装饰器
<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>
输出结果:

浙公网安备 33010602011771号