Weex

weex 组件通信

2017-02-24  本文已影响1375人  有情怀的程序猿
官方文档中其实就有介绍组件通信, 我这里写下我自己的理解

1: 定义一个方法:
可以在任何组件中定义方法:

this.$on(type, handler)

type: 是监听的自定义事件类型(官方解释) , 我认为是你给方法起个标示的名字,在其他地方可以获取到(了解的不够深, 说错了麻烦纠正下)
handler: 事件处理函数, 事件处理函数中第一个参数是事件对象$event, 详见我的数据绑定

2: 其他的 ViewModel 中获取这个方法, (此 ViewModel 中必须引用该组件)

xxx.$emit(type, detail);    //调用某某组件中的方法(type)

1: xxx , 指的是定义方法的组件,
2: detail, 是需要传入的值

xxx获取组件的方式

</element>
<template>
<div>
<foo title="Hello" image-url="https://gtms02.alicdn.com/tps/i2/TB1QHKjMXXXXXadXVXX20ySQVXX-512-512.png"></foo>
<text if="eventType">event: {{eventType}} - {{eventDetail}}</text>
</div>
</template>
<script>
module.exports = {
data: {
eventType: '',
eventDetail: {}
},
created: function () {
this.$on('notify', function(event) {
// When a notify comes, this handler will be run.
// event.detail will be {a: 1}
this.eventType = event.type
this.eventDetail = JSON.stringify(event.detail)
})
}
}
</script>

- 父级往子集传值
父级中引用了子集, 需要子组件的id

this.$vm(id).$emit(type, detail)

id为子集的id 类似获取节点

<element name="foo">
<template>
<div>
<image if="imageUrl" src="{{imageUrl}}" class="thumb"></image>
<text>Foo</text>
</div>
</template>
<style>
.thumb { width: 200; height: 200; }
</style>
<script>
module.exports = {
data: {
imageUrl: ''
},
created: function() {
this.$on('changeImage', function (e) {
this.imageUrl = e.detail
}.bind(this))
}
}
</script>
</element>
<template>
<div>
<foo id="sub"></foo>
<text onclick="test">click to update foo</text>
</div>
</template>
<script>
module.exports = {
methods: {
test: function (e) {
this.$vm('sub').$emit(
'changeImage',
'https://gtms02.alicdn.com/tps/i2/TB1QHKjMXXXXXadXVXX20ySQVXX-512-512.png'
)
}
}
}
</script>

上一篇 下一篇

猜你喜欢

热点阅读