微信小程序中的事件绑定

前言:

微信小程序中的事件绑定和Vue中的事件绑定其实有很多的相似之处,所以如果有过Vue相关的经验,学起来的话还是比较容易的。

js代码:

// 页面级的js文件必须调用Page函数来注册页面,
// 否则你的页面将无法正常渲染

Page({
  parent() {
    console.log('parent')
  },
  father() {
    console.log('father')
  },
  son() {
    console.log('son')
  }
})

wxss代码: (也就是对应的样式)

.parent{
  width: 500rpx;
  height: 500rpx;
  background-color: red;
  margin-bottom: 20rpx;
}

.father{
  width: 300rpx;
  height: 300rpx;
  background-color: pink;
}

.son{
  width: 100rpx;
  height: 100rpx;
  background-color: yellow;
}

wxml代码:

<!-- bind绑定的事件具有 事件冒泡 -->
<view class="parent" bind:tap="parent">
  <view class="father" bind:tap="father">
    <view class="son" bind:tap="son"></view>
  </view>
</view>

<!-- catch绑定的事件会阻止事件的冒泡 -->
<view class="parent" catch:tap="parent">
  <view class="father" catch:tap="father">
    <view class="son" catch:tap="son"></view>
  </view>
</view>

<!-- capture-bind 绑定的事件具有 事件捕获 -->
<view class="parent" capture-bind:tap="parent">
  <view class="father" capture-bind:tap="father">
    <view class="son" capture-bind:tap="son"></view>
  </view>
</view>

<!-- capture-catch 绑定的事件会阻止事件捕获 -->
<!-- 但是这样的话,在内部嵌套的元素永远无法触发对应的事件处理函数 -->
<view class="parent" capture-catch:tap="parent">
  <view class="father" capture-catch:tap="father">
    <view class="son" capture-catch:tap="son"></view>
  </view>
</view>

<!-- mut-bind绑定的事件具有 互斥效果,即"有我没你"的感觉 -->
<view class="parent" mut-bind:tap="parent">
  <view class="father" mut-bind:tap="father">
    <view class="son" mut-bind:tap="son"></view>
  </view>
</view>

总结:

  • 一般开发中的话用的比较多的是前两种
  • 如果会Vue中的指令的话,入手会很快