vue中使用裝飾器實現AOP編程

在JavaScript中實現AOP,是把一個函數“動態(tài)織入”到另一個函數之中。

首先要構造Function的prototype
prototype.js

Function.prototype.before = function (beforefn) {
  let _self = this;
  return function () {
    beforefn.apply(this, arguments);
    return _self.apply(this, arguments);
  };
};
Function.prototype.after = function (afterfn) {
  let _self = this;
  return function () {
    let ret = _self.apply(this, arguments);
    afterfn.apply(this, arguments);
    return ret;
  };
};
Function.prototype.around = function (beforefn, afterfn) {
  let _self = this;
  return function () {
    beforefn.apply(this, arguments);
    let ret = _self.apply(this, arguments);
    afterfn.apply(this, arguments);
    return ret;
  };
};

編輯我們的裝飾器函數
decorator.js

export const before = function (...args) {
  return function (target, key, descriptor) {
    descriptor.value = descriptor.value.before(() => {
      console.log(`Action-${key} 觸發(fā)埋點!`);
    });
  };
};
export const after = function (...args) {
  return function (target, key, descriptor) {
    descriptor.value = descriptor.value.after(() => {
      console.log(`Action-${key} 觸發(fā)埋點!`);
    });
  };
};
export const around = function (...args) {
  return function (target, key, descriptor) {
    descriptor.value = descriptor.value.around(() => {
      console.log(`Action-${key} 觸發(fā)埋點before!`);
    }, () => {
      console.log(`Action-${key} 觸發(fā)埋點after!`);
    });
  };
};

編輯我們的vue文件
test.vue

<template>
  <div></div>
</template>
<script>
import { before, after, around } from '@/lib/decorator';
export default {
  data () {
    
  },
  methods: {
    @before()
    @after()
    @around()
    errorHandle () {
      // 一些共用的異常處理方案
    }
  },
};
</script>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容