# 自定义装饰器

您可以通过创建自己的装饰器来扩展此库的功能。Vue 类组件提供 createDecorator 助手来创建自定义装饰器。createDecorator 期待一个回调函数作为第一个参数,回调函数将接收以下参数

  • options: Vue 组件选项对象。对该对象的更改将影响提供的组件。
  • key: 装饰器应用的属性或方法键。
  • parameterIndex: 如果自定义装饰器用于参数,则为装饰参数的索引。

创建 Log 装饰器的示例,该装饰器在调用装饰方法时打印带有方法名称和传递参数的日志消息

// decorators.js
import { createDecorator } from 'vue-class-component'

// Declare Log decorator.
export const Log = createDecorator((options, key) => {
  // Keep the original method for later.
  const originalMethod = options.methods[key]

  // Wrap the method with the logging logic.
  options.methods[key] = function wrapperMethod(...args) {
    // Print a log.
    console.log(`Invoked: ${key}(`, ...args, ')')

    // Invoke the original method.
    originalMethod.apply(this, args)
  }
})

将其用作方法装饰器

import Vue from 'vue'
import Component from 'vue-class-component'
import { Log } from './decorators'

@Component
class MyComp extends Vue {
  // It prints a log when `hello` method is invoked.
  @Log
  hello(value) {
    // ...
  }
}

在上面的代码中,当使用 42 调用 hello 方法时,将打印以下日志

Invoked: hello( 42 )