Weex 2.0实现了W3C标准的事件冒泡机制。
用法
<template>
<div class="root" @click="rootClick" bubble="true">
<text style="font-size: 40px;">{{rootText}}</text>
<div class="outer" @click="parentClick">
<div>
<text style="font-size: 40px;">{{parentText}}</text>
</div>
<text class="inner" @click="click">{{innerText}}</text>
</div>
</div>
</template>
<script>
module.exports = {
data: {
innerText: 'click me',
parentText: '',
rootText: ''
},
methods: {
click: function(e) {
this.innerText = 'inner bubble'
},
parentClick: function(e) {
this.parentText = 'parent bubble'
},
rootClick: function(e) {
this.rootText = 'root bubble'
}
}
}
</script>
<style scoped>
.inner {
font-size: 40px;
text-align: center;
background-color: #7a9b1b;
padding: 40px;
}
.outer {
font-size: 40px;
text-align: center;
background-color: #9b7a1b;
padding: 120px;
}
.root {
font-size: 40px;
text-align: center;
background-color: #7a1b9b;
padding: 80px;
}
</style>
注意
有一件事应该注意:为了与以前的版本兼容,Weex默认不打开事件冒泡。您需要添加bubble = "true"根元素的属性来打开冒泡机制。否则,事件不会向上传播,保持与前一版本相同的效果。
stopPropagation
在事件处理函数中,可以使用该e.stopPropagation()方法来防止事件升级。注意e.stopPropagation()不同于bubble = "true",只影响当前元素和父元素的传播,不影响子元素的传播; 后者是为了兼容性而添加的切换机制,将会是全局关闭或者开放的机制,两者可以共存,如下所示:
<template>
<div class="root" @click="rootClick" bubble="true">
<text style="font-size: 40px;">{{rootText}}</text>
<div class="outer" @click="parentClick">
<div>
<text style="font-size: 40px;">{{parentText}}</text>
</div>
<text class="inner" @click="click">{{innerText}}</text>
</div>
</div>
</template>
<script>
module.exports = {
data: {
innerText: 'click me',
parentText: '',
rootText: ''
},
methods: {
click: function(e) {
this.innerText = 'inner bubble'
},
parentClick: function(e) {
this.parentText = 'parent bubble'
e.stopPropagation()
},
rootClick: function(e) {
this.rootText = 'root bubble'
// e.stopPropagation()
}
}
}
</script>
<style scoped>
.inner {
font-size: 40px;
text-align: center;
background-color: #7a9b1b;
padding: 40px;
}
.outer {
font-size: 40px;
text-align: center;
background-color: #9b7a1b;
padding: 120px;
}
.root {
font-size: 40px;
text-align: center;
background-color: #7a1b9b;
padding: 80px;
}
</style>