一. 小程序的事件监听
二. 常见事件类型划分
三. 事件对象 event 属性分析 详见微信开放文档
当某个事件触发时, 会产生一个事件对象, 并且这个对象被传入到回调函数中
<view id="outer" class="outer" data-name="cap" bindtap="onOuterViewTap">
<view id="inner" class="inner"></view>
</view>
- target 触发事件的元素 ( inner )
- currentTarget 处理事件的元素( outer) 事件冒泡,两者作用在同一个元素上无差别,小程序中常用currentTarget
四. 事件参数传递方法
视图层发生事件时,某些情况需要事件携带一些参数到执行的函数中, 这个时候就可以通过data-属性来完成:
- 格式:data-属性的名称
- 获取:e.currentTarget.dataset.属性的名称
- 用{{ }}动态添加class
- 当前tap的下划线 通过包装一个text 设置border-bottom实现
案例
<!-- tab-control案例(重要) -->
<view class="tab-control">
<block wx:for="{{ titles }}" wx:key="*this">
<view
class="item {{index === currentIndex ? 'active': ''}}"
bindtap="onItemTap"
data-index="{{index}}"
>
<text class="title">{{ item }}</text>
</view>
</block>
</view>
Page({
data: {
titles: ["手机", "电脑", "iPad", "相机"],
currentIndex: 0
},
onItemTap(event) {
const currentIndex = event.currentTarget.dataset.index
//console.log(currentIndex);
this.setData({ currentIndex })
},
})
/* tab-control */
.tab-control {
display: flex;
height: 40px;
line-height: 40px;
text-align: center;
}
.tab-control .item {
flex: 1;
}
.tab-control .item.active {
color: #ff8189;
}
.tab-control .item.active .title {
border-bottom: 3px solid #ff8189;
padding: 5px;
}
五. 冒泡和捕获的区别
<view class="view1" capture-bind:tap="onView1CaptureTap" bindtap="onView1Tap">
<view class="view2" capture-bind:tap="onView2CaptureTap" bindtap="onView2Tap">
<view class="view3" capture-bind:tap="onView3CaptureTap" bindtap="onView3Tap">
</view>
</view>
</view>
// 捕获和冒泡过程
onView1CaptureTap() {
console.log("onView1CaptureTap");
},
onView2CaptureTap() {
console.log("onView2CaptureTap");
},
onView3CaptureTap() {
console.log("onView3CaptureTap");
},
onView1Tap() {
console.log("onView1Tap");
},
onView2Tap() {
console.log("onView2Tap");
},
onView3Tap() {
console.log("onView3Tap");
},
- bind 事件会继续往下传递
- catch 事件会阻止事件进一步传递