一、props与$emit 组件间的通信 、原则上可以实现所有组件见的参数传递
父 => 子
//父组件
<children :toChildren='toChildren' :toChildren1="toChildren1" />
//子组件
props:{
toChildren: {
type: Number || String || Array || object,
//可传递参数类型,最好明确类型。也可以type: [Number, String, Array ,Object]。
default: () => {
return 0 || '' || [] || {} //为了严谨,父组件没传递参数时给到的默认值。
}
},
toChildren1:{} //同上
},
子 => 父
//父组件
<children @childByValue='childByValue'/>
methods:{
childByValue(val){
this.toChild = val
//可以绑定父组件传递给其他兄弟组件的参数,并实现兄弟组件传参
}
}
//子组件
<input type="button" @click="childButtom" value="传值到父组件">
methods:{
childButtom(){
this.$emit('childByValue',this.childValue)
}
}
二、事件总线EventBus
EventBus简介
EventBus 又称为事件总线,在Vue中可以使用 EventBus来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件, 所以㢟都可以上下平行地通知其他组件,但也就是太方便了,所以使用不慎,就会造成难以维护的“灾难””,因此才需要Vuex作为状态管理中心,将通知的概念上升到共享状态层次
前言:eventBus可以说让人又爱又恨,正如简介中介绍的初始用的人无不大呼一声真香,它的语法的的简单直接,效果明显,无不让用它的人逐步上瘾,随之就会迎来eventBus的当头一棒,好像在说,小子你还年轻。(话不多说直接上代码)
//main.js 全局引用
Vue.prototype.$EventBus = new Vue()
//或者
import Vue from 'vue'
const EventBus = new Vue()
//两种皆可本文使用第一种引用方式
//绑定传递
<template>
<div>
<button @click="checkName()">EventBus传参</button>
</div>
</template>
<script>
export default {
data(){
return{
}
},
mounted(){},
methods:{
checkName(){
this.$EventBus.$emit('eventName', ' - 父组件的EventBus')
},
}
}
</script>
//监听
<template>
<div>
<p>{{childrenName}}</p>
</div>
</template>
<script>
export default {
data(){
return{
childrenName:''
}
},
mounted(){
//添加监听事件'eventName'
this.$EventBus.$on('eventName',(children)=>{
this.childrenName = children
})
},
beforeDestroy(){
//移除监听事件'eventName'
this.$EventBus.$off("eventName")
}
}
</script>
重点!重点!重点!
A组件只向EventBus发送了一次事件,但B组件却进行了多次监听,EventBus容器中有很多个一模一样的事件监听器这时就会出现,事件只触发一次,但监听事件中的回调函数执行了很多次
beforeDestroy(){
//移除监听事件"eventName"
this.$EventBus.$off("eventName")
}
总之,AB组件如果层级过深,或者毫无关联,需要点对点传参数,那么就用它!用它!用它!肯定爽到你''深田里敲钉桩''。
网友评论