vue 裝飾器

VUE組件中使用裝飾器, 使用@符號方式,總有些不盡人意, 如在裝飾器中對VUE組件綁定對象data的使用等,以下是一種解決辦法

//裝飾器
export const commandBefore = function (func) {
  if (typeof func !== 'function') {
    throw new TypeError('被裝飾的必須是函數');
  }
  const wrappedFunc = function (...args) {
    const [that, ok] = [...args];
   	//that爲當前vue組件對象,可以像在組件中使用this一樣隨意
    //TODO SOMETHING Before
    func(item)   //item參數傳向被裝飾函數
	//TODO SOMETHING Affter
    });
  };
  return wrappedFunc;
};

讓代碼優雅一些

/**
 * 裝飾函數
 * @param {*} func 被裝飾的函數
 * @param {*} decorator 裝飾器
 */
const decorateFunction = (func, decorator) => {
  return decorator(func);
};

vue組件中使用

methods: {
   test(){
       const _this = this;
       const f = decorateFunction(_resume, commandBefore);
       f(_this); //this 當前組件對象傳向裝飾函數
   
       //被裝飾函數對象
       function _resume(item) {
           //TODO SOMETHING
       }
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章