装饰器


1.方法装饰器

(1)节流防抖

import { throttle, debounce } from 'lodash'

// 节流 export const throttle = function(wait, options = {}) { return function(target, name, descriptor) { descriptor.value = throttle(descriptor.value, wait, options) } }
// 防抖 export const debounde
= function(wait, options = {}) { return function(target, name, descriptor) { descriptor.value = debounde (descriptor.value, wait, options) } }

(2)Loading

import { Toast } from 'vant'

export const loading =  function(message = '加载中...', errorFn = function() {}) {
     return function(target, name, descriptor){
         const fn = descriptor.value
          descriptor.value = async function(...rest){
               const loading = Toast.loading({
                    message: message,
                    forbidClick: true
               })
               try{
                    return await fn.call(this, ...rest)
               }catch(e){
                     errorFn && errorFn.call(this, error, ...rest)
                     console.error(error)
               }finally{
                     loading.clear()
               }
          }
     
     }
}                    

(3)确认框

import { Dialog } from 'vant'
export function confirm(message = '确定要删除数据,此操作不可回退。',title = '提示',cancelFn = function() {
     return function(target, name, descriptor){
          const originFn = descriptor.value
          descriptor.value = async function(...rest) {
               try{
                  await Dialog..confirm({
                     message,
                     title: title
                  }) 
                  originFn.apply(this, rest)
               }catch(e){
                  cancelFn && cancelFn(error)
               }
          }
  }
}        

2.类装饰器

// 这个是要混入的对象
const methods = {
  logger() {
    console.log('记录日志')
  }
}
function mixins(obj) { return function (target) { Object.assign(target.prototype, obj) } } // 这个是一个登陆登出类 @mixins(methods) class Login{ login() {} logout() {} }