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>
复制代码

输出结果:

 

posted on   独自去流浪  阅读(1779)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示