两个组件如何通信?
Closed this issue · 2 comments
henryzp commented
A和B两个组件
A组件如果想调用B组件里面的方法,该怎么写?
如:
var Head = Regular.extend({
})
var Content = Regular.extend({
})
Head里面有一个按钮操作,需要去调用Content里面的方法,要改变Content里面的一些数据
想过提取公共方法,但B里面的方法,涉及到B页面的一些操作。
leeluolee commented
如果都是像你这样命令式调用的,那有几种
- 主动声明,
var head = new Head;
var content = new Content;
content.$on('xx', function(){
head.xx....
})
head.$on('xx', function(){
content.xx....
})
- 引入中介者模式
var emitter = new Regular; // 什么都不做,只发事件
var Head = Regular.extend({
config: function() { // 视情况选择在config或init,或其他实际监听
emitter.$on('content某个event', function(){})
}
})
var Content = Regular.extend({
config: function(){
emitter.$on('head某个event', function(){})
}
})
如果你是声明式初始化,
- 可以将emitter传入作为中介者,其他类似上面
new Regular({
template: `
<head emitter={emitter} />
<content emitter = {emitter} />
`,
data: {
emitter: new Regular
}
})
- 使用ref, ref除了拿dom节点也能拿组件
new Regular({
template: `
<head ref=head/>
<content ref=content />
`,
init: function(){
this.$refs.head.$on('xxx');
}
})
其实还有一些方式,无外乎一些常用通信的设计模式。自己去摸索下吧, 不过Regular目前是不支持向下的事件broadcast.
henryzp commented
好的,谢谢 @leeluolee