# 小程序的事件
事件是视图层到逻辑层的通讯方式,可以将用户的行为反馈到逻辑层进行处理。事件可以绑定在组件上,触发事件后,就会执行逻辑层中对应的事件处理函数。小程序的事件对象可以查看自定义属性的值
# bind 和 catch
小程序通过 bind*/catch*
(*代表事件类型) 给组件添加事件;bind
方式绑定的事件会向上冒泡,catch
方式绑定的事件不会向上冒泡
<!-- 点击 inner view 会先后调用handleTap3和handleTap2(因为tap事件会冒泡到 middle view,而 middle view 阻止了 tap 事件冒泡,不再向父节点传递),点击 middle view 会触发handleTap2,点击 outer view 会触发handleTap1 -->
<view id="outer" bindtap="handleTap1">
outer view
<view id="middle" catchtap="handleTap2">
middle view
<view id="inner" bindtap="handleTap3">
inner view
</view>
</view>
</view>
常见事件类型:toushstart touchmove touchcancel touchend tap longpress longtap transitionend animationstart animationiteration animationend touchforcechange
小程序表单、swiper 等组件有自己的事件类型,详情参见官方 API 各组件详细内容事件介绍
通过事件改变页面 data
对象内容的方式
<!-- index.wxml -->
<button bindtap="changeCount">{{count}}</button>
<!-- index.js -->
page({ data{ count: 0 }, changeCount: function (){ this.setData({ count: this.data.count ++ }) } })
# 事件的捕获阶段
需要在捕获阶段监听事件时,可以采用capture-bind
、capture-catch
关键字,后者将中断捕获阶段和取消冒泡阶段
在下面的代码中,点击 inner view 会先后调用handleTap2
、handleTap4
、handleTap3
、handleTap1
<view id="outer" bind:touchstart="handleTap1" capture-bind:touchstart="handleTap2">
outer view
<view id="inner" bind:touchstart="handleTap3" capture-bind:touchstart="handleTap4">
inner view
</view>
</view>
如果将上面代码中的第一个capture-bind
改为capture-catch
,将只触发handleTap2
<view id="outer" bind:touchstart="handleTap1" capture-catch:touchstart="handleTap2">
outer view
<view id="inner" bind:touchstart="handleTap3" capture-bind:touchstart="handleTap4">
inner view
</view>
</view>