事件
原创...大约 3 分钟
事件是视图层到逻辑层的通讯方式
事件可以将用户的行为反馈到逻辑层进行处理
事件可以绑定在组件上,当达到触发事件,就会执行逻辑层中对应的事件处理函数
事件对象可以携带额外信息,如 id, dataset, touches
事件的使用方式
<button type="primary" bindtap="tapName">Click me!</button>
<view bindtap="tapName"> Click me! </view>
Page({
tapName() {
console.log("点击");
},
});
Event 对象
在小程序中,也具有事件对象 event
Page({
tapName(e) {
console.log(e);
},
});
属性 | 类型 | 说明 |
---|---|---|
type | String | 事件类型 |
timeStamp | Integer | 事件生成时的时间戳 |
target | Object | 触发事件的组件的一些属性值集合 |
currentTarget | Object | 当前组件的一些属性值集合 |
mark | Object | 事件标记数据 |
detail | Object | 额外的信息 |
touches | Array | 触摸事件,当前停留在屏幕中的触摸点信息的数组 |
changedTouches | Array | 触摸事件,当前变化的触摸点信息的数组 |
事件分类
事件分为冒泡事件和非冒泡事件:
- 冒泡事件(bind):当一个组件上的事件被触发后,该事件会向父节点传递
- 非冒泡事件(catch):当一个组件上的事件被触发后,该事件不会向父节点传递
冒泡事件(bind)
当一个组件上的事件被触发后,该事件会向父节点传递
<view bindtap="bindParentHandle">
<button type="primary" bindtap="bindChildHandle">冒泡事件</button>
</view>
Page({
bindParentHandle() {
console.log("父级事件");
},
bindChildHandle() {
console.log("子级事件");
},
});
执行顺序为:子级事件,父级事件
非冒泡事件(catch)
当一个组件上的事件被触发后,该事件不会向父节点传递
<view catchtap="catchParentHandle">
<button type="primary" catchtap="catchChildHandle">非冒泡事件</button>
</view>
Page({
catchParentHandle() {
console.log("非冒泡父级事件");
},
catchChildHandle() {
console.log("非冒泡子级事件");
},
});
执行顺序为:非冒泡子级事件 (父级的并没有被触发)
事件类型
在微信小程序中,事件有很多中类型,通过 bind 和 catch 与下面的类型组合产生不同类型的事件
类型 | 触发条件 |
---|---|
touchstart | 手指触摸动作开始 |
touchmove | 手指触摸后移动 |
touchcancel | 手指触摸动作被打断,如来电提醒,弹窗 |
touchend | 手指触摸动作结束 |
tap | 手指触摸后马上离开 |
longpress | 手指触摸后,超过 350ms 再离开,如果指定了事件回调函数并触发了这个事件,tap 事件将不被触发 |
longtap | 手指触摸后,超过 350ms 再离开(推荐使用 longpress 事件代替) |
<button type="primary" bindtouchstart="bindtouchStartHandle">
touchstart bind
</button>
<button type="primary" catchtouchstart="catchtouchStartHandle">
touchstart catch
</button>
<button type="primary" bindlongpress="bindlongpressHandle">
longpress bind
</button>
<button type="primary" catchlongpress="catchlongpressHandle">
longpress catch
</button>
Page({
bindtouchStartHandle() {
console.log("bind与touchStart组合");
},
catchtouchStartHandle() {
console.log("catch与touchStart组合");
},
bindlongpressHandle() {
console.log("bind与longpress组合");
},
catchlongpressHandle() {
console.log("catch与longpress组合");
},
});
事件携带参数
事件在触发的过程中,我们可以携带参数
- event 对象中的 currentTarget 读取携带参数
- event 对象中的 mark 读取携带参数
currentTarget 携带参数
在组件节点中可以附加一些自定义数据。这样,在事件中可以获取这些自定义的节点数据,用于事件的逻辑处理。
<view data-id="1001" bindtap="bindViewTap"> 携带参数 </view>
Page({
bindViewTap(e: any) {
console.log(e.currentTarget.dataset.id);
},
});
mark 携带参数
可以使用 mark 来识别具体触发事件的 target 节点。此外, mark 还可以用于承载一些自定义数据(类似于 dataset )。
当事件触发时,事件冒泡路径上所有的 mark 会被合并,并返回给事件回调函数。(即使事件不是冒泡事件,也会 mark 。)
<view mark:parentMark="父级" bindtap="bindMarkTap">
<button type="primary" mark:childMark="子级" bindtap="bindButtonTap">
按钮
</button>
</view>
Page({
bindMarkTap(e: any) {
console.log(e.mark);
},
bindButtonTap(e: any) {
console.log(e.mark);
},
});
Powered by Waline v2.15.7