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>
輸出結果:

