首页 文章 精选 留言 我的

精选列表

搜索[js框架],共10000篇文章
优秀的个人博客,低调大师

【Vue.js】873- Vue 3.0 进阶之指令探秘

在 Vue 的项目中,我们经常会遇到 v-if、v-show、v-for 或 v-model 这些内置指令,它们为我们提供了不同的功能。除了使用这些内置指令之外,Vue 也允许注册自定义指令。 接下来,阿宝哥将使用 Vue 3 官方文档 自定义指令 章节中使用的示例,来一步步揭开自定义指令背后的秘密。 提示:在阅读本文前,建议您先阅读 Vue 3 官方文档 自定义指令 章节的内容。 一、自定义指令 1、注册全局自定义指令 constapp=Vue.createApp({})//注册一个全局自定义指令v-focusapp.directive('focus',{//当被绑定的元素挂载到DOM中时被调用mounted(el){//聚焦元素el.focus()}}) 2、使用全局自定义指令 <divid="app"><inputv-focus/></div> 3、完整的使用示例 <divid="app"><inputv-focus/></div><script>const{createApp}=Vueconstapp=Vue.createApp({})//①app.directive('focus',{//②//当被绑定的元素挂载到DOM中时被调用mounted(el){el.focus()//聚焦元素}})app.mount('#app')//③</script> 当页面加载完成后,页面中的输入框元素将自动获得焦点。该示例的代码比较简单,主要包含 3 个步骤:创建 App 对象、注册全局自定义指令和应用挂载。其中创建 App 对象的细节,阿宝哥会在后续的文章中单独介绍,下面我们将重点分析其他 2 个步骤。首先我们先来分析注册全局自定义指令的过程。 二、注册全局自定义指令的过程 在以上示例中,我们使用 app 对象的 directive 方法来注册全局自定义指令: app.directive('focus',{//当被绑定的元素挂载到DOM中时被调用mounted(el){el.focus()//聚焦元素}}) 当然,除了注册全局自定义指令外,我们也可以注册局部指令,因为组件中也接受一个 directives 的选项: directives:{focus:{mounted(el){el.focus()}}} 对于以上示例来说,我们使用的 app.directive 方法被定义在 runtime-core/src/apiCreateApp.ts 文件中: //packages/runtime-core/src/apiCreateApp.tsexportfunctioncreateAppAPI<HostElement>(render:RootRenderFunction,hydrate?:RootHydrateFunction):CreateAppFunction<HostElement>{returnfunctioncreateApp(rootComponent,rootProps=null){constcontext=createAppContext()letisMounted=falseconstapp:App=(context.app={//省略部分代码_context:context,//用于注册或检索全局指令。directive(name:string,directive?:Directive){if(__DEV__){validateDirectiveName(name)}if(!directive){returncontext.directives[name]asany}if(__DEV__&&context.directives[name]){warn(`Directive"${name}"hasalreadybeenregisteredintargetapp.`)}context.directives[name]=directivereturnapp},returnapp}} 通过观察以上代码,我们可以知道 directive 方法支持以下两个参数: name:表示指令的名称; directive(可选):表示指令的定义。 name 参数比较简单,所以我们重点分析 directive 参数,该参数的类型是 Directive 类型: //packages/runtime-core/src/directives.tsexporttypeDirective<T=any,V=any>=|ObjectDirective<T,V>|FunctionDirective<T,V> 由上可知 Directive 类型属于联合类型,所以我们需要继续分析 ObjectDirective 和 FunctionDirective 类型。这里我们先来看一下 ObjectDirective 类型的定义: //packages/runtime-core/src/directives.tsexportinterfaceObjectDirective<T=any,V=any>{created?:DirectiveHook<T,null,V>beforeMount?:DirectiveHook<T,null,V>mounted?:DirectiveHook<T,null,V>beforeUpdate?:DirectiveHook<T,VNode<any,T>,V>updated?:DirectiveHook<T,VNode<any,T>,V>beforeUnmount?:DirectiveHook<T,null,V>unmounted?:DirectiveHook<T,null,V>getSSRProps?:SSRDirectiveHook} 该类型定义了对象类型的指令,对象上的每个属性表示指令生命周期上的钩子。而 FunctionDirective 类型则表示函数类型的指令: //packages/runtime-core/src/directives.tsexporttypeFunctionDirective<T=any,V=any>=DirectiveHook<T,any,V>exporttypeDirectiveHook<T=any,Prev=VNode<any,T>|null,V=any>=(el:T,binding:DirectiveBinding<V>,vnode:VNode<any,T>,prevVNode:Prev)=>void 介绍完 Directive 类型,我们再回顾一下前面的示例,相信你就会清晰很多: app.directive('focus',{//当被绑定的元素挂载到DOM中时触发mounted(el){el.focus()//聚焦元素}}) 对于以上示例,当我们调用 app.directive 方法注册自定义 focus 指令时,就会执行以下逻辑: directive(name:string,directive?:Directive){if(__DEV__){//避免自定义指令名称,与已有的内置指令名称冲突validateDirectiveName(name)}if(!directive){//获取name对应的指令对象returncontext.directives[name]asany}if(__DEV__&&context.directives[name]){warn(`Directive"${name}"hasalreadybeenregisteredintargetapp.`)}context.directives[name]=directive//注册全局指令returnapp} 当 focus 指令注册成功之后,该指令会被保存在 context 对象的 directives 属性中,具体如下图所示: 顾名思义 context 是表示应用的上下文对象,那么该对象是如何创建的呢?其实,该对象是通过 createAppContext 函数来创建的: constcontext=createAppContext() 而 createAppContext 函数被定义在 runtime-core/src/apiCreateApp.ts 文件中: //packages/runtime-core/src/apiCreateApp.tsexportfunctioncreateAppContext():AppContext{return{app:nullasany,config:{isNativeTag:NO,performance:false,globalProperties:{},optionMergeStrategies:{},isCustomElement:NO,errorHandler:undefined,warnHandler:undefined},mixins:[],components:{},directives:{},provides:Object.create(null)}} 看到这里,是不是觉得注册全局自定义指令的内部处理逻辑其实挺简单的。那么对于已注册的 focus 指令,何时会被调用呢?要回答这个问题,我们就需要分析另一个步骤 —— 应用挂载。 三、应用挂载的过程 为了更加直观地了解应用挂载的过程,阿宝哥利用 Chrome 开发者工具,记录了应用挂载的主要过程: 通过上图,我们就可以知道应用挂载期间所经历的主要过程。此外,从图中我们也发现了一个与指令相关的函数 resolveDirective。很明显,该函数用于解析指令,且该函数在 render 方法中会被调用。在源码中,我们找到了该函数的定义: //packages/runtime-core/src/helpers/resolveAssets.tsexportfunctionresolveDirective(name:string):Directive|undefined{returnresolveAsset(DIRECTIVES,name)} 在 resolveDirective 函数内部,会继续调用 resolveAsset 函数来执行具体的解析操作。在分析 resolveAsset 函数的具体实现之前,我们在 resolveDirective 函数内部加个断点,来一睹 render 方法的 “芳容”: 在上图中,我们看到了与 focus 指令相关的 _resolveDirective("focus") 函数调用。前面我们已经知道在 resolveDirective 函数内部会继续调用 resolveAsset 函数,该函数的具体实现如下: //packages/runtime-core/src/helpers/resolveAssets.tsfunctionresolveAsset(type:typeofCOMPONENTS|typeofDIRECTIVES,name:string,warnMissing=true){constinstance=currentRenderingInstance||currentInstanceif(instance){constComponent=instance.type//省略解析组件的处理逻辑constres=//局部注册resolve(instance[type]||(ComponentasComponentOptions)[type],name)||//全局注册resolve(instance.appContext[type],name)returnres}elseif(__DEV__){warn(`resolve${capitalize(type.slice(0,-1))}`+`canonlybeusedinrender()orsetup().`)}} 因为注册 focus 指令时,使用的是全局注册的方式,所以解析的过程会执行 resolve(instance.appContext[type], name) 该语句,其中 resolve 方法的定义如下: functionresolve(registry:Record<string,any>|undefined,name:string){return(registry&&(registry[name]||registry[camelize(name)]||registry[capitalize(camelize(name))]))} 分析完以上的处理流程,我们可以知道在解析全局注册的指令时,会通过 resolve 函数从应用的上下文对象中获取已注册的指令对象。在获取到 _directive_focus 指令对象后,render 方法内部会继续调用 _withDirectives 函数,用于把指令添加到 VNode 对象上,该函数被定义在 runtime-core/src/directives.ts 文件中: //packages/runtime-core/src/directives.tsexportfunctionwithDirectives<TextendsVNode>(vnode:T,directives:DirectiveArguments):T{constinternalInstance=currentRenderingInstance//获取当前渲染的实例constinstance=internalInstance.proxyconstbindings:DirectiveBinding[]=vnode.dirs||(vnode.dirs=[])for(leti=0;i<directives.length;i++){let[dir,value,arg,modifiers=EMPTY_OBJ]=directives[i]//在mounted和updated时,触发相同行为,而不关系其他的钩子函数if(isFunction(dir)){//处理函数类型指令dir={mounted:dir,updated:dir}asObjectDirective}bindings.push({dir,instance,value,oldValue:void0,arg,modifiers})}returnvnode} 因为一个节点上可能会应用多个指令,所以 withDirectives 函数在 VNode 对象上定义了一个 dirs 属性且该属性值为数组。对于前面的示例来说,在调用 withDirectives 函数之后,VNode 对象上就会新增一个 dirs 属性,具体如下图所示: 通过上面的分析,我们已经知道在组件的 render 方法中,我们会通过 withDirectives 函数把指令注册对应的 VNode 对象上。那么 focus 指令上定义的钩子什么时候会被调用呢?在继续分析之前,我们先来介绍一下指令对象所支持的钩子函数。 一个指令定义对象可以提供如下几个钩子函数 (均为可选): created:在绑定元素的属性或事件监听器被应用之前调用。 beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。 mounted:在绑定元素的父组件被挂载后调用。 beforeUpdate:在更新包含组件的 VNode 之前调用。 updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。 beforeUnmount:在卸载绑定元素的父组件之前调用。 unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。 介绍完这些钩子函数之后,我们再来回顾一下前面介绍的 ObjectDirective 类型: //packages/runtime-core/src/directives.tsexportinterfaceObjectDirective<T=any,V=any>{created?:DirectiveHook<T,null,V>beforeMount?:DirectiveHook<T,null,V>mounted?:DirectiveHook<T,null,V>beforeUpdate?:DirectiveHook<T,VNode<any,T>,V>updated?:DirectiveHook<T,VNode<any,T>,V>beforeUnmount?:DirectiveHook<T,null,V>unmounted?:DirectiveHook<T,null,V>getSSRProps?:SSRDirectiveHook} 好的,接下来我们来分析一下 focus 指令上定义的钩子什么时候被调用。同样,阿宝哥在 focus 指令的 mounted 方法中加个断点: 在图中右侧的调用栈中,我们看到了 invokeDirectiveHook 函数,很明显该函数的作用就是调用指令上已注册的钩子。出于篇幅考虑,具体的细节阿宝哥就不继续介绍了,感兴趣的小伙伴可以自行断点调试一下。 四、阿宝哥有话说 4.1 Vue 3 有哪些内置指令? 在介绍注册全局自定义指令的过程中,我们看到了一个 validateDirectiveName 函数,该函数用于验证自定义指令的名称,从而避免自定义指令名称,与已有的内置指令名称冲突。 //packages/runtime-core/src/directives.tsexportfunctionvalidateDirectiveName(name:string){if(isBuiltInDirective(name)){warn('Donotusebuilt-indirectiveidsascustomdirectiveid:'+name)}} 在 validateDirectiveName 函数内部,会通过 isBuiltInDirective(name) 语句来判断是否为内置指令: constisBuiltInDirective=/*#__PURE__*/makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text') 以上代码中的 makeMap 函数,用于生成一个 map 对象(Object.create(null))并返回一个函数,用于检测某个 key 是否存在 map 对象中。另外,通过以上代码,我们就可以很清楚地了解 Vue 3 中为我们提供了哪些内置指令。 4.2 指令有几种类型? 在 Vue 3 中指令分为 ObjectDirective 和 FunctionDirective 两种类型: //packages/runtime-core/src/directives.tsexporttypeDirective<T=any,V=any>=|ObjectDirective<T,V>|FunctionDirective<T,V> ObjectDirective exportinterfaceObjectDirective<T=any,V=any>{created?:DirectiveHook<T,null,V>beforeMount?:DirectiveHook<T,null,V>mounted?:DirectiveHook<T,null,V>beforeUpdate?:DirectiveHook<T,VNode<any,T>,V>updated?:DirectiveHook<T,VNode<any,T>,V>beforeUnmount?:DirectiveHook<T,null,V>unmounted?:DirectiveHook<T,null,V>getSSRProps?:SSRDirectiveHook} FunctionDirective exporttypeFunctionDirective<T=any,V=any>=DirectiveHook<T,any,V>exporttypeDirectiveHook<T=any,Prev=VNode<any,T>|null,V=any>=(el:T,binding:DirectiveBinding<V>,vnode:VNode<any,T>,prevVNode:Prev)=>void 如果你想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将回调函数传递给指令来实现: app.directive('pin',(el,binding)=>{el.style.position='fixed'consts=binding.arg||'top'el.style[s]=binding.value+'px'}) 4.3 注册全局指令与局部指令有什么区别? 注册全局指令 app.directive('focus',{//当被绑定的元素挂载到DOM中时被调用mounted(el){el.focus()//聚焦元素}}); 注册局部指令 constComponent=defineComponent({directives:{focus:{mounted(el){el.focus()}}},render(){const{directives}=this.$options;return[withDirectives(h('input'),[[directives.focus,]])]}}); 解析全局注册和局部注册的指令 //packages/runtime-core/src/helpers/resolveAssets.tsfunctionresolveAsset(type:typeofCOMPONENTS|typeofDIRECTIVES,name:string,warnMissing=true){constinstance=currentRenderingInstance||currentInstanceif(instance){constComponent=instance.type//省略解析组件的处理逻辑constres=//局部注册resolve(instance[type]||(ComponentasComponentOptions)[type],name)||//全局注册resolve(instance.appContext[type],name)returnres}} 4.4 内置指令和自定义指令生成的渲染函数有什么区别? 要了解内置指令和自定义指令生成的渲染函数的区别,阿宝哥以 v-if 、v-show 内置指令和 v-focus 自定义指令为例,然后使用 Vue 3 Template Explorer 这个在线工具来编译生成渲染函数: v-if 内置指令 <inputv-if="isShow"/>const_Vue=Vuereturnfunctionrender(_ctx,_cache,$props,$setup,$data,$options){with(_ctx){const{createVNode:_createVNode,openBlock:_openBlock,createBlock:_createBlock,createCommentVNode:_createCommentVNode}=_VuereturnisShow?(_openBlock(),_createBlock("input",{key:0})):_createCommentVNode("v-if",true)}} 对于 v-if 指令来说,在编译后会通过 ?: 三目运算符来实现动态创建节点的功能。 v-show 内置指令 <inputv-show="isShow"/>const_Vue=Vuereturnfunctionrender(_ctx,_cache,$props,$setup,$data,$options){with(_ctx){const{vShow:_vShow,createVNode:_createVNode,withDirectives:_withDirectives,openBlock:_openBlock,createBlock:_createBlock}=_Vuereturn_withDirectives((_openBlock(),_createBlock("input",null,null,512/*NEED_PATCH*/)),[[_vShow,isShow]])}} 以上示例中的 vShow 指令被定义在 packages/runtime-dom/src/directives/vShow.ts 文件中,该指令属于 ObjectDirective 类型的指令,该指令内部定义了 beforeMount、mounted、updated 和 beforeUnmount 四个钩子。 v-focus 自定义指令 <inputv-focus/>const_Vue=Vuereturnfunctionrender(_ctx,_cache,$props,$setup,$data,$options){with(_ctx){const{resolveDirective:_resolveDirective,createVNode:_createVNode,withDirectives:_withDirectives,openBlock:_openBlock,createBlock:_createBlock}=_Vueconst_directive_focus=_resolveDirective("focus")return_withDirectives((_openBlock(),_createBlock("input",null,null,512/*NEED_PATCH*/)),[[_directive_focus]])}} 通过对比 v-focus 与 v-show 指令生成的渲染函数,我们可知 v-focus 自定义指令与 v-show 内置指令都会通过 withDirectives 函数,把指令注册到 VNode 对象上。而自定义指令相比内置指令来说,会多一个指令解析的过程。 此外,如果在 input 元素上,同时应用了 v-show 和 v-focus 指令,则在调用 _withDirectives 函数时,将使用二维数组: <inputv-show="isShow"v-focus/>const_Vue=Vuereturnfunctionrender(_ctx,_cache,$props,$setup,$data,$options){with(_ctx){const{vShow:_vShow,resolveDirective:_resolveDirective,createVNode:_createVNode,withDirectives:_withDirectives,openBlock:_openBlock,createBlock:_createBlock}=_Vueconst_directive_focus=_resolveDirective("focus")return_withDirectives((_openBlock(),_createBlock("input",null,null,512/*NEED_PATCH*/)),[[_vShow,isShow],[_directive_focus]])}} 4.5 如何在渲染函数中应用指令? 除了在模板中应用指令之外,利用前面介绍的 withDirectives 函数,我们可以很方便地在渲染函数中应用指定的指令: <divid="app"></div><script>const{createApp,h,vShow,defineComponent,withDirectives}=VueconstComponent=defineComponent({data(){return{value:true}},render(){return[withDirectives(h('div','我是阿宝哥'),[[vShow,this.value]])]}});constapp=Vue.createApp(Component)app.mount('#app')</script> 本文阿宝哥主要介绍了在 Vue 3 中如何自定义指令、如何注册全局和局部指令。为了让大家能够更深入地掌握自定义指令的相关知识,阿宝哥从源码的角度分析了指令的注册和应用过程。 在后续的文章中,阿宝哥将会介绍一些特殊的指令,当然也会重点分析一下双向绑定的原理,感兴趣的小伙伴不要错过哟。 五、参考资源 Vue 3 官网 - 自定义指令 Vue 3 官网 - 应用 API 聚焦全栈,专注分享 TypeScript、Web API、前端架构等技术干货。 本文分享自微信公众号 - 前端自习课(FE-study)。如有侵权,请联系 support@oschina.cn 删除。本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

优秀的个人博客,低调大师

JS明明写的请求是并行,为何仍然串行请求?

环境 测试环境:electron + vue + axios 需求 想要做并行请求(比如爬虫)需要尽量快的请求页面。 假如一次发出请求到返回所需时间为100ms: 方案1(串行):请求一次接口等待返回处理结果后继续下一次请求。这样会受制于请求的速度,假如请求100次那么需要总时间为100ms * 100 = 10000ms 方案2(并行):利用Promise,同时发起多个请求,但不等待每个请求结束。而是Promise.all等待其全部结束再进行处理。假如请求100次那么需要总时间为100ms * 1= 100ms 可以看出速度有极大的提升,理论上(实际需要看机器配置和网络带宽情况)无论多少请求都只需要100ms。 并行实现 我们的需求就是方案2的并行实现。所以如下实现: async t () { const time1 = new Date().getTime() / 1000 const task = [] for (let i=0; i < 100; i++){ task.push(this.t1()) // 发起请求 } await Promise.all(task) // 等待所有请求结束 // await this.$http.all(task) // 与Promise一样 const time2 = new Date().getTime() / 1000 console.log('time:', time2 - time1) }, async t1 () { const res = await this.$http({ method: 'get', baseURL: this.url, url: LOGIN_PATH, // 关键:正常url }) } 结果仍然是串行? 查看console程序的time输出很高,是所有请求时间累加的时间。 查看network,从time和waterfall也可以明显看出, 所有请求的开始时间点是一样的 但是后续请求都有等待时间(灰色),都是上一个请求开始到结束时间 每个请求的真正时间(绿色)几乎一样,但总时长越往后请求越慢,都是上一个请求结束才开始下一个 以上看出完全是串行请求,并没有达到我们的预期 network图如下: 问题在哪? 我们都知道浏览器中请求都应该是并行的,html中加载网络文件和请求也通常都是并行的。 观察发现这里所有经过url都是一致的,而一般网页开发时很少出现一个页面请求多次同样的url的,所以这里很可疑。 经过尝试,将每次url都改为不完全一样,确实解决了此问题。(怀疑是浏览器的问题,非axios问题。而之后使用node版的got未发现此问题) 修改代码,请求的url增加随机参数使其完整url每次都发生变化,修改部分代码如下: async t1 () { const res = await this.$http({ method: 'get', baseURL: this.url, // url: LOGIN_PATH, // 关键:正常url url: LOGIN_PATH + `?v=${Math.random()}`, // 关键:增加随机参数 }) } 查看console的程序输出时间已经为几乎只有一个请求的时间。 查看network所有请求也都同时开始,也几乎(网络因素影响,不可能每次时间都一样)同时结束,总耗时只有200ms多 查询资料及测试发现,“chrome + jquery”并行请求看起来是6个一块,与资料所述chrome浏览器http最大连接数为6一致,基本可以判定这次主要问题在于浏览器或者electron(实际扔使用的chrome内核)连接数有关,还有些问题,比如如何修改连接数等这里不再深究。一些参考资料如下: 浏览器同域名请求的最大并发数限制 浏览器HTTP请求并发数和TCP连接的关系 electron中使用got未发现此问题,这个库是node环境库,可能不经过chrome内核

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册