微信小程序:用户交互核心—js

123 阅读2分钟

用户交互核心—js

快速入门示例

通过 bind + 事件类型,例如下面的 bindtap 就是绑定了一个 tap 类型的事件

<view class="test" bindtap="tapHandle">
  <text class="abc">this is a test</text>
</view>

接下来在 Page 构造函数中,书写对应的事件处理函数。

在事件处理函数中,会自动传入一个参数,该参数就是事件对象。

Page({
  data: {
    // ...
  },
  // 事件处理函数
  // 会自动传入一个参数,该参数为此次事件对应的事件对象
  tapHandle(e){
    console.log('你触发了点击事件');
    console.log(e);
  }
})

事件类型

在上面的示例中,我们绑定的是一个 tap 事件,它是在点击的时候触发。

具体有的事情,如下表所示:

image-20230111100549023

更多的事件类型,请参阅官方文档:developers.weixin.qq.com/ebook?actio…

longtap 和 longpress 的区别在于,如果同时还绑定了 tap 事件,那么longpress并不会再次触发tap事件,而longtap则会再次触发tap事件。

事件对象

我们在前面的例子中,看到了事件对象会自动传入到事件处理函数。

image-20230111100833539

我们先来看 detail,这个可以获取一些额外的信息:

image-20230111101214305

target 和 currentTarget:

  • currentTarget:为当前事件所绑定的组件
  • target:则是触发该事件的源头组件。

示例如下:

<view class="outter" bindtap="tapHandle2" data-id="outter">
  <view class="innter" data-id="innter"></view>
</view>
tapHandle2(e){
    console.log("target: ",e.target);
    console.log("currentTarget: ",e.currentTarget);
 }

效果如下:

image-20230111102258282

事件冒泡以及阻止冒泡

首先,在小程序中的事件,如果是采用的 bind 进行的绑定,会和 DOM 的事件流一样,有一个事件冒泡的行为:

<view class="outter" bindtap="outtertap" data-id="outter">
  <view class="innter" data-id="innter" bindtap="innertap"></view>
</view>
outtertap(e){
  console.log("触发了 outter 事件");
},
innertap(){
  console.log("触发了 inner 事件");
}

在上面的代码中,如果我们针对 inner 进行点击,那么,事件会一直向上冒泡,outter 组件的 tap 事件也会触发。

可以通过 catch 来绑定事件,使用 catch 绑定的事件,不会向上冒泡。

示例如下:

<view class="outter" bindtap="outtertap" data-id="outter">
  <view class="middle" catchtap="middletap" data-id="middle">
    <view class="inner" data-id="inner" bindtap="innertap"></view>
  </view>
</view>
outtertap(){
  console.log("触发了 outter 事件");
},
middletap(){
  console.log("触发了 middle 事件");
},
innertap(){
  console.log("触发了 inner 事件");
}

在上面的示例中,因为 inner 是使用 bind 来绑定的,所以会向上冒泡,触发 middle 的 tap 事件,但是 middle 绑定 tap 事件的时候,使用的是 catch 来绑定,catch 会阻止冒泡。

事件捕获

从基础哭 1.5.0 开始,bind 和事件类型之间可以加一个冒号

例如以前是 bindtap="事件处理函数",就可以写作 bind:tap="事件处理函数"

如果想要使用事件捕获,可以通过 capture-bind 来绑定事件,示例代码如下:

<view class="outter" capture-bind:tap="outtertap" data-id="outter">
  <view class="middle" capture-bind:tap="middletap" data-id="middle">
    <view class="inner" data-id="inner" capture-bind:tap="innertap"></view>
  </view>
</view>

这节课结束之后,请通读官方文档对应的:developers.weixin.qq.com/ebook?actio…