应用场景:当父组件需要触发子组件的事件时,可以使用broadcast。(父组件中有头部搜索条件,子组件渲染搜索结果,当父组件点击了搜索按钮,那么父组件所有的子组件需要请求后台,重新渲染搜索结果)
父组件:
<template>
<div class="search-item">
<Button type="primary" size="large" @click.stop="searchevent">查询</Button>
</div>
<child1></child1>
<child2></child2>
</template>
<script>
searchevent(){
//broadcast方法是vue实例中自带的
this.broadcast(['child1','child2'],"search",{
//要带到子组件的参数
classId:this.classId
})
}
</script>
//子组件
methods{
request(){
//请求数据,触发重新渲染页面
}
},
//在created生命周期中写入接收广播过来的search事件
created(){
this.$on("search",parmas=>{
//parmas这个对象中就携带了父组件带过来的参数
this.classId=parmas.classId
//触发request
this.request()
})
}