JS装饰器如何在项目中使用

JS 装饰器概述

JavaScript 装饰器是一种以 @ 符号开头的特殊语法,放在目标代码的前面用于包装或扩展代码功能。

JavaScript 的装饰器语法目前仍处于提案阶段,现阶段使用的话需要通过 babel 等方式进行编译之后,才能在浏览器正常运行。

装饰器分为两种:类装饰器,类成员装饰器,分别用于装饰 类以及类的成员。

语法

装饰器语法分为两部分。

首先是装饰器的定义,装饰器定义是编写一个函数,函数会接受所装饰的内容作为参数。

类装饰器和类型成员装饰器只是在接收的参数上不同。

而装饰器的使用则是使用 @ 符号加上定义的装饰器名称(即装饰器的函数名)

kotlin 复制代码
// 定义一个类装饰器
const classDecorator = (target) => {
	// do something
}

// 使用装饰器
@classDecorator
class Human {
}

类装饰器

类装饰器接收一个参数,即类的本身。

typescript 复制代码
const classDecorator = (target) => {
	console.log(`species is ${target.species}`); // species is human
}

// 使用装饰器
@classDecorator
class Human {
	static species = 'human';
}

类成员装饰器

类成员可以是类的属性,方法,或者是 getter 或 setter 等;类成员装饰器函数接收三个参数,分别是类本身,成员名称,成员修饰符(就是表示属性的是否可枚举,可读,可配置等的对象)

ini 复制代码
const speciesDecorator = (target, name, descriptor) => {
  console.log({ target, name, descriptor });
}

class Human {
  @speciesDecorator
  static species = 'Human';
}

装饰器输出结果为:

比如我们可以利用 descriptor 这个参数来做限制属性为不可枚举

typescript 复制代码
const speciesDecorator = (target, name, descriptor) => {
  console.log({ target, name, descriptor });
  descriptor.enumerable = false; // 将属性变为不可枚举
}

class _Human {
  static species = 'Human';
}
console.log(Object.keys(_Human)); // ['species']

class Human {
  @speciesDecorator
  static species = 'Human';
}
console.log(Object.keys(Human)); // []

同时使用多个装饰器

装饰器是可以叠加使用的,使用多个装饰器只需要在代码前面添加多个装饰器的使用即可

ini 复制代码
const noEnumerable = (target, name, descriptor) => {
  // 将属性改为不可枚举
  descriptor.enumerable = false;
}

const readonly = (target, name, descriptor) => {
  // 将属性改为只读
  descriptor.writable = false;
}


class Human {
  @noEnumerable
  @readonly
  static species = 'human';
}

console.log(Object.keys(Human)); // []
console.log(Human.species); // human
Human.species = 'new human';
console.log(Human.species); // human

装饰器的执行顺序

  • 装饰器在类定义时即执行

  • 先执行类成员装饰器,类成员装饰器执行完后,再执行类装饰器

  • 类成员装饰器的先后执行取决于成员的定义顺序

typescript 复制代码
const classDecorator = (target) => {
  console.log('类装饰器执行')
}

const speciesDecorator_1 = (target, name, descriptor) => {
  console.log('species_1 装饰器执行')
}

const speciesDecorator_2 = (target, name, descriptor) => {
  console.log('species_2 装饰器执行')
}

// 使用装饰器
@classDecorator
class Human {
  @speciesDecorator_1
	static species_1 = 'human';
  @speciesDecorator_2
	static species_2 = 'human';
}

执行结果为:

species_1 装饰器执行

species_2 装饰器执行

类装饰器执行

如何在vite项目中使用decorator

  • 安装两个包
css 复制代码
 p i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties
  • vite配置
php 复制代码
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [
          ["@babel/plugin-proposal-decorators", { legacy: true }],
          ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
      },
    }),
  ],
});
相关推荐
GISer_Jing1 分钟前
jx前端架构学习
前端·学习·架构
间彧30 分钟前
Tailwind CSS详解
前端
间彧31 分钟前
Headless UI详解
前端
han_1 小时前
Vue.js 为什么要推出 Vapor Mode?
前端·javascript·vue.js
oden1 小时前
AI重构10000行老代码:2周完成1个月工作量的真实复盘
前端·aigc·ai编程
小满zs2 小时前
Next.js第十二章(RSC/服务端组件/客户端组件)
前端
亿元程序员2 小时前
明明直接用就可以了,非要在Creator里面写???
前端
wadesir2 小时前
Nginx负载均衡代理协议详解(从零开始搭建高可用Web服务)
前端·nginx·负载均衡
秋氘渔2 小时前
Vue 3 组合式写法:侦听器 watch 和 watchEffect 的区别及使用技巧
前端·javascript·vue.js·watch·watcheffect
想睡八个小时2 小时前
已包含的文件名 “a.vue“ 仅大小写与文件名 “A.vue“ 不同
前端·vscode