vue、react不同组件怎么通信
Vue
- 父子组件:props、$refs、$children
- 子父组件:$parent、$emit自定义事件
- 如果项目够复杂,可能需要Vuex等全局状态管理库通信
- 非父子组件用Event Bus通信($emit、$on)
1 | //main.js |
- $dispatch(vue2已经废除)和$broadcast(vue2已经废除)
React
- 父子组件:props,如果父组件与子组件之间不止一个层级,可通过…运算符(Object 剩余和展开属性)。
1 | class Child_1 extends Component{ |
- 子父组件:props回调方法
- 项目复杂的话用Redux、Mobx等全局状态管理管库
- 非父子组件,用发布订阅模式的Event模块
- 用新的Context Api
- 父组件首先声明自己可以支持 context,定义 childContextTypes 方法。
- 父组件需要定义方法,返回 context 对象,定义 getChildContext 方法。
- 子组间声明自己需要使用 context,定义 contextTypes 方法。
Event Bus
- 它实际上是发布订阅模式。
- 实现流程
- 实现类class
1
2
3
4
5
6class EventEmeitter{
constructor(){
this._evt = this._evt || new Map();
this._maxListener = this._maxListener || 10;
}
}- 监听和触发
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class EventEmeitter{
emit(type, ...args){
let handler;
handler = this._evt.get(type); //new Map()方法
if (args.length > 0) {
handler.apply(this, args);
} else {
handler.call(this);
}
return true;
}
on(type, fn){
if (!this._evt.get(type)) {
this._evt.set(type, fn);
}
}