微信小程序事件绑定

2019-10-04  本文已影响0人  椰果粒

事件绑定

简单的点击事件:

<view>{{counter}}</view>
<button size="mini" bindtap="handleIncrease">+</button>
<button size="mini" bindtap="handleDecrease">-</button>

handleIncrease(){
  this.setData({
    counter: this.data.counter + 1
  })
},
handleDecrease(){
  this.setData({
    counter: this.data.counter - 1
  })
}

有的组件有自己特有的事件,比如input或者scroll-view
input有bindinput,bindfocus,bindblur
scroll-view有bindscrolltpwrapper,bindscrolltolower

所有组件都有的事件:

事件 触发条件
touchstart 手指触摸动作开始
touchmove 手指滑动
touchcancel 手指触摸被打断(比如来电了)
touchend 手指触摸结束
tap 点击事件
longpress 长按,超过350毫秒,并且这个和tap不能同时触发,只会执行一个

点击一下,会触发touchstart,tap,touchend
长按会触发:touchstart,longpress,touchend
这俩是不能同时触发到的。

bindtap与catchtap都表示点击,他俩的区别是:

举个例子:

<view 
    class="container"
    bind:touchstart="handleTouchStart"
    bind:touchmove="hendleTouchMove"
    bind:touchcancel="handleTouchCancel"
    bind:touchend="handleTouchEnd"
    bind:tap="handleTap"
    bind:longpress="handleLongpress"
></view>
handleTouchStart(){
  console.log("touchStart");
},
handleTouchMove(){
  console.log("touchMove");
},
handleTouchCancel(){
  console.log("touchCancel");
},
handleTouchEnd(){
  console.log("touchEnd");
},
handleTap(){
  console.log("tap");
},
handleLongpress(){
  console.log("longpress");
},

事件对象

当某个组件触发了一个事件的时候,就会产生一个事件对象(event),这个事件对象有很多属性。这个事件对象会被传入到回调函数中。

事件对象的属性 属性值 描述
type tap/touchstart...
currentTarget
target
detail x,y 鼠标点击的位置
timestapes 从页面打开到我触发事件经过了多长时间
changedTouches
touches

touches和changedTouches的区别:
touches:记录了有几个手指在屏幕上触摸了
changedTouches:记录手指的变化,有几个手指发生了变化。

在什么时候能看到他们的区别:

target和currentTarget的区别:

举个例子:
获取事件对象:

<button bind:tap="handleClick">点击获取事件对象</button>
handleClick(event){
  console.log(event);
},

事件的传递参数

比如我想给点击事件传递一个参数,应该怎么做:

通过data-的形式传递参数

<!-- 事件传递参数,传递index和item -->
<block wx:for="{{titles}}" wx:key="{{index}}">
  <view 
    bind:tap="handleClickTitle"
    data-index="{{index}}"
    data-item="{{item}}"
  >{{item}}</view>
</block>
// 获取传递过来的参数
handleClickTitle(event){
  console.log(event)
  const dataset = event.currentTarget.dataset;
  const index = dataset.index;
  const item = dataset.item;
  console.log(index, item);
}

事件捕获和事件冒泡

当组件产生一个事件的时候,事件分了事件捕获和事件冒泡。这和原生的是一样的。

顺序是:先捕获后冒泡,先从外往里再往外。

会一层层传递:bind
捕获:capture-bind:tap
冒泡:bind:tap

不会一层层传递,阻止事件的进一步传递:catch
就是阻止冒泡和阻止捕获(后续都被阻止掉了)
捕获:capture-catch:tap
冒泡:catch:tap

上一篇 下一篇

猜你喜欢

热点阅读