三步带你玩转前端Vue装饰器

  • 什么是装饰器
  • 装饰器怎么封装
  • 装饰器能干啥

1、什么是装饰器

看个例子就懂了eg:
正常开发是这样的:
    1、先定义节流方法:
        methods: {
          throttle (func, delay) {            
              var timer = null;            
              return function() {                
                  var context = this;               
                  var args = arguments;                
                  if (!timer) {                    
                      timer = setTimeout(function() {             
                          func.apply(context, args);               
                          timer = null;                    
                      }, delay);                
                  }            
              }        
          }    
        }
        2、然后执行A方法:
        methods: {
             a() {
                this.throttle(()=>{
                 //执行业务逻辑
                }, 400)
            }
        }
反正就是各种嵌套,看起来代码很脓肿,接下来看看【装饰器】怎么写↓
//使用装饰器过后的写法
import { throttle} from "@/utils/decorator";

methods: {
  @throttle(400)  // 装饰器(节流)  
  a() {
    // 执行业务逻辑
    //此时会发现点击效果跟上面写法一样
    console.log('执行业务')
  },
}
现在看到的写法是不是凉快了很多,没有多层嵌套

2、装饰器怎么封装

    1、在工具文件创建decorator.js
    // utils/decorator.js
    /**
     * 节流,一定时间内,只能触发一次操作
     * @export
     * @param {Function} fn - 运行函数
     * @param {Number} wait - 延迟时间
     * @returns
     */
    export function throttle(wait = 2000) {
      //返回值:被传递给函数的对象。    
      return function(target, name, descriptor) {
        // @param target 类本身
        // @param name 装饰的属性(方法)名称
        // @param descriptor 属性(方法)的描述对象
        const fn = descriptor.value 
        let canRun = true
        descriptor.value = async function(...args) {
          //具体的装饰器业务在这里面编写    
          if (!canRun) return
          await fn.apply(this, args) // 执行业务下的方法
          canRun = false
          setTimeout(() => {
            canRun = true
          }, wait)
        }
      }
    }
    2、在业务板块里面声明使用
       methods: {
          @throttle(400)  // 装饰器(节流)  
          a() {
            // 执行业务逻辑
            //此时会发现点击效果跟上面写法一样
            console.log('执行业务')
          },
        }
    //现在看到代码是不是就没有那么脓肿了,就一行指令

3、装饰器能干啥

现实开发中经常遇到节流,防抖,日志,按钮权限等等一些业务执行之前的拦截操作

以下是我平时使用的一些装饰器,希望对看到这里的你有帮助!
// utils/decorator.js
import { Dialog } from 'vant';

/**
 * loading 开关装饰器
 * @param {String} loading 当前页面控制开关的变量名字
 * @param {Function} errorCb 请求异常的回调 返回error 一般不用写
 * 如果 errorCb 为 function 为你绑定 this  如果是箭头函数 则第二个参数为this
 * @example
 * @loading('loading',function(){})
 * async getTab(){
 *  this.tab =  this.$apis.demo()
 * }
 */
export function loading (loading, errorCb = Function.prototype) {
  return function (target, name, descriptor) {
    const oldFn = descriptor.value;
    descriptor.value = async function (...args) {
      try {
        this[loading] = true;
        await oldFn.apply(this, args);
      } catch (error) {
        errorCb.call(this, error, this);
      } finally {
        this[loading] = false;
      }
    };
  };
}

/**
 * 日志注入
 * @export
 * @param {Function} fn - 运行函数
 * @param {data} 日志需要的参数
 * @returns
 */
export function log(data) {
  return function(target, name, descriptor) {
    const fn = descriptor.value;
    descriptor.value = async function(...args) {
      await fn.apply(this, args);
      logApi(data) // 自己的日志接口
    }
  }
}

// utils/decorator.js
/**
 * 节流,一定时间内,只能触发一次操作
 * @export
 * @param {Function} fn - 运行函数
 * @param {Number} wait - 延迟时间
 * @returns
 */
export function throttle(wait= 2000) {
  return function(target, name, descriptor) {
    const fn = descriptor.value
    let canRun = true
    descriptor.value = async function(...args) {
      if (!canRun) return
      await fn.apply(this, args)
      canRun = false
      setTimeout(() => {
        canRun = true
      }, wait)
    }
  }
}
// utils/decorator.js
/**
 * 防抖,连续操作时,只在最后一次触发
 * @export
 * @param {Function} fun - 运行函数
 * @param {Number} wait - 延迟时间
 * @returns
 */
export function debounce(wait= 2000) {
  return function(target, name, descriptor) {
    const fn = descriptor.value
    let timer = null
    descriptor.value = function(...args) {
      const _this = this._isVue ? this : target
      clearTimeout(timer)
      timer = setTimeout(() => {
        fn.apply(_this, args)
      }, wait)
    }
  }
}
/**
 * 表单校验
 * @param {String} formElKey - 表单el
 */
export const formValidation = (formElKey = 'formEl') => {
  return (target, name, descriptor) => {
    const method = descriptor.value
    descriptor.value = async function() {
      const _this = this._isVue ? this : target
      const isValidate = _this[formElKey]?.validate
      if (isValidate) {
        const [, res] = await to(isValidate())
        if (!res) return false
      }
      return method.apply(_this, arguments)
    }
  }
}
// utils/decorator.js
/**
 * 确认框
 * @param {String} title - 标题
 * @param {String} concent - 内容
 * @param {String} confirmButtonText - 确认按钮名称
 * @returns
 */
export const alertDecorator = ({title = '提示', message = '请输入弹窗内容', confirmButtonText = '我知道了'}) => {
  return (target, name, descriptor) => {
    const fn = descriptor.value;
    descriptor.value = function (...args) {
        Dialog.alert({title, message, confirmButtonText}).then(() => {
          fn.apply(this, args);
        });
    }
  }
}



/**
 * 缓存计算结果
 * @export
 * @param {Function} fn
 * @returns
 */
export function cached() {
  return function(target, name, descriptor) {
    const method = descriptor.value
    const cache = new Map()
    descriptor.value = function() {
      const _this = this._isVue ? this : target
      const key = JSON.stringify(arguments)
      if (!cache.has(key)) {
        cache.set(key, method.apply(_this, arguments))
      }
      return cache.get(key)
    }
  }
}
既然看到了这里,先收藏一下,如果实战划水时间提高了,别忘了回来点个赞哦
如果觉得有用,就分享给你的小伙伴吧!
接下来就是快乐的划水了 O(∩_∩)O哈哈~

座右铭是树袋熊

119 声望
10 粉丝
0 条评论
推荐阅读
Vue微信公众号开发踩坑记录
JS-SDK需要向服务端获取签名,且获取签名中需要的参数包括所在页面的url,但由于单页应用的路由特殊,其中涉及到iOS和android微信客户端浏览器内核的差异性导致的兼容问题

imwty132阅读 67.6k评论 81

从零搭建 Node.js 企业级 Web 服务器(零):静态服务
过去 5 年,我前后在菜鸟网络和蚂蚁金服做开发工作,一方面支撑业务团队开发各类业务系统,另一方面在自己的技术团队做基础技术建设。期间借着 Node.js 的锋芒做了不少 Web 系统,有的至今生气蓬勃、有的早已夭折...

乌柏木172阅读 13.9k评论 10

手把手教你写一份优质的前端技术简历
不知不觉一年一度的秋招又来了,你收获了哪些大厂的面试邀约,又拿了多少offer呢?你身边是不是有挺多人技术比你差,但是却拿到了很多大厂的offer呢?其实,要想面试拿offer,首先要过得了简历那一关。如果一份简...

tonychen152阅读 17.7k评论 5

封面图
正则表达式实例
收集在业务中经常使用的正则表达式实例,方便以后进行查找,减少工作量。常用正则表达式实例1. 校验基本日期格式 {代码...} {代码...} 2. 校验密码强度密码的强度必须是包含大小写字母和数字的组合,不能使用特殊...

寒青56阅读 8.4k评论 11

JavaScript有用的代码片段和trick
平时工作过程中可以用到的实用代码集棉。判断对象否为空 {代码...} 浮点数取整 {代码...} 注意:前三种方法只适用于32个位整数,对于负数的处理上和Math.floor是不同的。 {代码...} 生成6位数字验证码 {代码...} ...

jenemy48阅读 7k评论 12

从零搭建 Node.js 企业级 Web 服务器(十五):总结与展望
总结截止到本章 “从零搭建 Node.js 企业级 Web 服务器” 主题共计 16 章内容就更新完毕了,回顾第零章曾写道:搭建一个 Node.js 企业级 Web 服务器并非难事,只是必须做好几个关键事项这几件必须做好的关键事项就...

乌柏木75阅读 7.1k评论 16

再也不学AJAX了!(二)使用AJAX ① XMLHttpRequest
「再也不学 AJAX 了」是一个以 AJAX 为主题的系列文章,希望读者通过阅读本系列文章,能够对 AJAX 技术有更加深入的认识和理解,从此能够再也不用专门学习 AJAX。本篇文章为该系列的第二篇,最近更新于 2023 年 1...

libinfs42阅读 6.8k评论 12

封面图

座右铭是树袋熊

119 声望
10 粉丝
宣传栏