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

组件常用技术(Vue)

时间:2023-04-01 12:54:45 vue.js

1.组件通信,父组件传值=>子组件:attributeprops//childprops:{msg:String}//parent**referencerefs**//parentthis.$refs.hw.xxchildcomponent=>parentcomponent:customevent//childthis.$emit('add',good)//parent兄弟组件:通过公共祖先组件**通过公共祖先组件、$parent或$root桥接。//brother1this.$parent.$on('foo',handle)//brother2this.$parent.$emit('foo')Provide/injectbetweenancestorsanddescendants:Abilitytopassvaluesfromancestorstodescendants//祖先和后代之间提供/注入的能力//ancestorancestorEnteravalueinthegenerationprovide(){return{foo:'foo'}}//在后代中使用//descendantinject:['foo']dispatch:passvaluesfromdescendantstoancestors//定义一个dispatch方法指定要派发的事件名称和数据functiondispatch(eventName,data){letparent=this.$parent//只要父元素还存在,就继续往上查找while(parent){//父元素使用$emit触发parent.$emit(eventName,data)//递归查找父元素parent=parent.$parent}}//使用Helloword.vue{{msg}}App.vuethis.$on('hello',this.sayHello)任意两个组件之间:事件总线或vuex事件总线:创建负责事件的Bus类分发、监控和回调管理//Bus:事件派发、监听和回调管理类Bus{constructor(){//{//eventName1:[fn1,fn2],//eventName2:[fn3,fn4],//}this.callbacks={}}$on(name,fn){this.callbacks[名称]=this.callbacks[名称]||[]this.callbacks[name].push(fn)$emit(name,args){if(this.callbacks[name]){this.callbacks[name].forEach(cb=>cb(args))}}//main.jsVue.prototype.$bus=newBus()//child1this.$bus.$on('foo',handle)//child2this.$bus.$emit('foo')vuex:创建一个唯一的全局数据管理器通过它存储、管理数据并通知组件状态变化。Vue2.6.0之后,使用新的v-slot语法来替代之前的slot和slot-scope匿名slot

命名插槽
//parentnamedslot{{parentelementdata}}