当前位置: 首页 > Web前端 > vue.js

vue中组件通信之findComponents

时间:2023-03-31 22:41:50 vue.js

//查找组件上下文为当前组件上下文对象,componentName为组件名称constfindUpwardComponent=(context,componentName)=>{letparent=context.$parentletname=parent.$options.namewhile(parent&&(!name||!name.includes(componentName))){parent=parent.$parentif(parent)name=parent.$options.name}returnparent}//查找兄弟组件constfindBrotherComponents=(ctx,componentName,exceptMe=true)=>{const$brothers=ctx.$parent.$children.filter(item=>{returnitem.$options.name&&item.$options.name.includes(componentName)})constindex=$brothers.findIndex(item=>item._uid===ctx._uid)if(exceptMe&&index>-1)$broters.splice(index,1)return$broters}//往下看constfindDownwardComponent=(context,componentName)=>{const$children=上下文。$childrenletbean=nullif($children.length){for(constchildof$children){constname=child.$options.nameif(name&&name.includes(componentName)){bean=childbreak}else{bean=findDownwardComponent(child,componentName)if(bean)break}}}返回bean}