当前位置: 首页 > Web前端 > JavaScript

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

时间:2023-03-27 14:41:33 JavaScript

什么是装饰器装饰器是如何封装装饰器能做什么的1.什么是装饰器,看个例子就明白了eg:正常的开发是这样的:1.首先定义节流方法:methods:{throttle(func,延迟){vartimer=null;返回函数(){varcontext=this;var参数=参数;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('executebusiness')},}现在看到的写法是不是爽多了,不用多层嵌套2.如何封装装饰器1.在工具文件中创建decorator.js//utils/decorator.js/***节流,只需要一次操作一定时间内可以触发*@export*@param{Function}fn-运行函数*@param{Number}wait-延迟时间*@returns*/exportfunctionthrottle(wait=2000){//返回值:传递给函数的对象。returnfunction(target,name,descriptor){//@param目标类本身//@paramname装饰属性(方法)名称//@paramdescriptor属性(方法)描述对象constfn=descriptor.valueletcanRun=truedescriptor.value=asyncfunction(...args){//具体的装饰器业务写在这里if(!canRun)returnawaitfn.apply(this,args)//执行业务下的方法canRun=falsesetTimeout(()=>{canRun=true},wait)}}}2.在业务部分声明和使用方法:{@throttle(400)//Decorator(throttle)a(){//执行业务逻辑//这时候你会发现点击效果和上面一样lineofinstructions3.Decorator我能做什么在实际开发中,经常会遇到节流,防抖,日志,按钮权限等业务执行前的一些拦截操作以下是我平时使用的一些decorator,希望大家多多指教对看到这个的你有帮助!//utils/decorator.jsimport{Dialog}from'vant';/***加载开关装饰器*@param{String}当前页面控制开关加载变量名*@param{Function}errorCb请求异常回调返回错误一般不需要写*如果errorCb是一个函数,就给你绑定这个。如果是箭头函数,第二个参数就是this*@example*@loading('loading',function(){})*asyncgetTab(){*this.tab=this.$apis.demo()*}*/exportfunctionloading(loading,errorCb=Function.prototype){返回函数(target,name,descriptor){constoldFn=descriptor.value;descriptor.value=asyncfunction(...args){try{this[loading]=true;等待oldFn.apply(this,args);}catch(error){errorCb.call(this,error,this);}最后{this[loading]=false;}};};}/***日志注入*@export*@param{Function}fn-运行函数*@param{data}日志所需的参数*@returns*/exportfunctionlog(data){returnfunction(target,name,descriptor){constfn=descriptor.value;descriptor.value=asyncfunction(...args){awaitfn.apply(this,args);logApi(data)//自己的日志接口}}}//utils/decorator.js/***节流,一定时间内,只触发一次操作*@export*@param{Function}fn-runfunction*@param{Number}等待-延迟时间*@returns*/exportfunctionthrottle(wait=2000){returnfunction(target,name,descriptor){constfn=descriptor.valueletcanRun=truedescriptor.value=asyncfunction(...args){if(!canRun)returnawaitfn.apply(this,args)canRun=falsesetTimeout(()=>{canRun=true},wait)}}}//utils/decorator.js/***防抖,连续运行时只在最后一次触发*@export*@param{Function}fun-运行函数*@param{Number}wait-延迟时间*@returns*/exportfunctiondebounce(wait=2000){returnfunction(target,name,descriptor){constfn=descriptor.valuelettimer=nulldescriptor.value=function(...args){const_this=this._isVue?this:targetclearTimeout(timer)timer=setTimeout(()=>{fn.apply(_this,args)},wait)}}}/***表单验证*@param{String}formElKey-formel*/exportconstformValidation=(formElKey='formEl')=>{return(target,name,descriptor)=>{constmethod=descriptor.valuedescriptor.value=asyncfunction(){const_this=this._isVue?this:targetconstisValidate=_this[formElKey]?.validateif(isValidate){const[,res]=awaitto(isValidate())if(!res)返回false}returnmethod.apply(_this,arguments)}}}//utils/decorator.js/***确认框*@param{String}title-标题*@param{String}concent-内容*@param{String}confirmButtonText-确认按钮名称*@returns*/exportconstalertDecorator=({title='提示',message='请输入弹窗内容',confirmButtonText='我知道'})=>{return(target,name,descriptor)=>{constfn=descriptor.value;descriptor.value=function(...args){Dialog.alert({title,message,confirmButtonText}).then(()=>{fn.apply(this,args);});}}}/***缓存计算结果*@export*@param{Function}fn*@returns*/exportfunctioncached(){returnfunction(target,name,descriptor){constmethod=descriptor.valueconstcache=newMap()descriptor.value=function(){const_this=this._isVue?this:targetconstkey=JSON.stringify(arguments)if(!cache.has(key)){cache.set(key,method.apply(_this,arguments))}returncache.get(key)}}}现在如果您看过此内容,请先将其添加为书签。如果实际行程时间增加了,别忘了回来点个赞哦。如果您觉得有用,请分享给您的朋友!接下来就是开心划水O(∩_∩)O哈哈~