decorator.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // 定义装饰器
  2. function Component(metaData: {
  3. selector: string;
  4. template: string;
  5. style: { [key: string]: string };
  6. }) {
  7. return function (Constructor: Function) {
  8. // 修改类的原型,添加 render 方法
  9. Constructor.prototype.render = function () {
  10. let compList = document.querySelectorAll(this.selector);
  11. compList.forEach((element) => {
  12. // 应用样式
  13. Object.keys(this.style).forEach((key) => {
  14. element.style[key] = this.style[key];
  15. });
  16. // 插入模板内容
  17. element.innerHTML = this.template;
  18. });
  19. };
  20. // 初始化类的属性
  21. Constructor.prototype.selector = metaData.selector;
  22. Constructor.prototype.style = metaData.style;
  23. Constructor.prototype.template = metaData.template;
  24. };
  25. }
  26. // 定义一个接口来描述 Component 的结构
  27. interface IComponent {
  28. selector: string;
  29. template: string;
  30. style: { [key: string]: string };
  31. render(): void;
  32. }
  33. // 创建具体的组件类
  34. @Component({
  35. selector: "card",
  36. style: {
  37. margin: "10px",
  38. border: "solid 1px",
  39. minWidth: "100px",
  40. minHeight: "80px",
  41. },
  42. template: "我是卡片",
  43. })
  44. class CardComponent implements IComponent {
  45. selector: string;
  46. template: string;
  47. style: { [key: string]: string };
  48. // 现在 render 方法是由装饰器注入的
  49. render(): void {
  50. // 这个方法会被装饰器覆盖
  51. }
  52. }
  53. @Component({
  54. selector: "circle",
  55. style: {
  56. margin: "10px",
  57. border: "solid 1px",
  58. borderRadius: "50%",
  59. width: "100px",
  60. height: "80px",
  61. },
  62. template: "我是圆形",
  63. })
  64. class CircleComponent implements IComponent {
  65. selector: string;
  66. template: string;
  67. style: { [key: string]: string };
  68. // 现在 render 方法是由装饰器注入的
  69. render(): void {
  70. // 这个方法会被装饰器覆盖
  71. }
  72. }
  73. // 渲染组件
  74. const cardInstance = new CardComponent();
  75. cardInstance.render();
  76. const circleInstance = new CircleComponent();
  77. circleInstance.render();