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

VUE组件通信总结

时间:2023-04-01 01:08:57 vue.js

1.父组件与子组件通信(parenttochild)属性props//parent//childprops:{info:String}refs//parentthis.$refs.hw.xxx='xxxx'//这里xxx对应Helloworld子组件ps中的数据:注意在创建的父组件中不能获取到子组件的ref,因为父组件是在子组件之前创建的,并没有挂载和渲染DOM。一般子元素$children//parentthis.$children[index].xx='xxx'ps:注意子元素的顺序是不保证的,也不是响应式的,改值没问题,但是不要尝试修改或替换子树,它是只读的2.子组件与父组件的通信自定义事件:在子组件中分发一个事件,在父组件中监听并处理(观察者模式?)//Childthis.$emit('add',count)//Parent//这里是Cart组件上监听的,谁派谁监听3.兄弟组件communication通过共同的祖先,$parentor$root(commonparentorcommonroot)//parent//Child//通过parent分发,监听应该由父组件完成,可以通过created(){this通过parent在t中监听hechildcomponent.$parent.$on('biu',()=>{console.log('biubiubiu~~~')})}4.祖先和后代(跨代传参)由于嵌套层数过多,传props不实用,Vue提供provide/injectAPI来完成==>实现祖先传值给后代,反过来不适用,常用于组件库开发//ancestorprovide(){returnfoo:'foo'}//{foo:'foo'}objectfunctioncanbecomponent:{}//descendantinject:['foo']//numbergroupprops:{}5.任意两个组件之间的通信:eventbus或vuexeventbus:创建一个Bus类负责事件派发、监听和回调管理//类似于$parent和$root作为中介,通过一个独立的VueExample作为中介//Bus事件分发、监听和回调管理---栗子1类Bus{constructor(){this.callbacks={}}}$on(name,fn){this.callbacks[name]=this.callback[name]||[]this.callbacks[name].push(fn)}$emit(name,args){if(this.callbacks[name]){this.callbacks[name].forEach(cb=>cb(args))}}Vue.prototype.$bus=newBus()//main.jsthis.$bus.$on('foo',handle)//child1this.$bus.$emit('foo')//child2栗子2:importVuefrom'vue';exportdefaultnewVue();//bus.jsimportBus...;Bus.$emit('goBank',data)//child1import总线...;公共汽车。$on('goBank',res=>{})6.Vuex:创建一个全局唯一的状态管理,管理数据并通知组件状态变化Slot:Vue实现的内容分发API,用于复合组件开发该技术是在通用组件中使用库开发中有无数的应用。(基本parent-->child)1.Anonymousslothello//父组件传过来的值显示在子组件slot

//comp12.namedslot分发内容到子组件的指定位置//parentnamedslotcontentslot
//comp2
3.子组件中应该使用scopeslot分布contentData(data是从子组件传递过来)//parent//指定v-slot的值作为作用域上下文对象{{slotProps.foo}}//解构用法,foo对象有bla,bar{{bla}}
//comp3