Vue的通讯的方式:
- props、emit(最常用的父子通讯方式)
父组件传入属性,子组件通过props接收,就可以在内部this.XXX的方式使用
子组件$emit(事件名,传递的参数)向外弹出一个自定义事件, 在父组件中的属性监听事件,同时也能获取子组件传出来的参数
// 父组件
<hello-world msg="hello world!" @confirm="handleConfirm"><hello-world>
// 子组件
props: {
msg: {
type: String,
default: ''
}
},
methods:{
handleEmitParent(){
this.$emit('confirm', list)
}
}
- 事件总线 EventBus (常用任意两个组件之间通讯)
原理:注册的事件存起来,等触发事件时再调用。定义一个类去处理事件,并挂载到Vue实例的this上即可注册和触发事件,也可拓展一些事件管理
class Bus {
constructor () {
this.callbackList = {
}
}
$on (name, callback) {
// 注册事件
this.callbackList[name] ? this.callbackList[name].push(callback) :

本文总结了Vue中组件之间的多种通讯方式,包括props和emit进行父子通讯,EventBus实现任意组件间通讯,Vuex进行状态管理,以及通过$refs、parent/root、$children、attrs/listeners、provide/inject等实现复杂场景下的组件交互。了解这些方法有助于提升Vue应用的灵活性和可维护性。
&spm=1001.2101.3001.5002&articleId=118387990&d=1&t=3&u=8b8905fc4acb4e568a829cc7d63f36c2)
1213

被折叠的 条评论
为什么被折叠?



