微信小程序事件绑定基本语法

微信小程序使用 bind 或 catch 前缀绑定事件,语法如下:

<组件 bind事件名="处理函数" catch事件名="处理函数"></组件>
  • bind:事件绑定,允许事件冒泡(向父组件传递)。

  • catch:事件绑定,阻止事件冒泡(不会向父组件传递)。

常见事件类型

事件名说明适用组件
tap点击事件viewbutton
input输入框内容变化inputtextarea
submit表单提交form
scroll滚动事件scroll-view
longpress长按事件(350ms)viewbutton

二、事件绑定示例

1. 点击事件(bindtap / catchtap

<!-- 点击事件(允许冒泡) -->
<view bindtap="handleTap">点击我</view>

<!-- 阻止冒泡 -->
<view catchtap="handleNoBubbleTap">点击我(不冒泡)</view>
Page({
  handleTap() {
    console.log("点击事件触发");
  },
  handleNoBubbleTap() {
    console.log("点击事件触发,但不会冒泡");
  }
});

2. 输入事件(bindinput

<input bindinput="handleInput" placeholder="输入内容" />
Page({
  handleInput(e) {
    console.log("输入内容:", e.detail.value);
  }
});

3. 表单提交(bindsubmit

<form bindsubmit="handleSubmit">
  <input name="username" placeholder="用户名" />
  <button form-type="submit">提交</button>
</form>
Page({
  handleSubmit(e) {
    console.log("表单数据:", e.detail.value);
  }
});

三、事件对象(event

事件处理函数的参数 event 包含以下关键属性:

属性说明
type事件类型(如 tapinput
target触发事件的组件(原始事件源)
currentTarget当前绑定事件的组件
detail额外信息(如输入框的值)
timeStamp事件触发时间戳
touches触摸点信息(多指触控)

获取 data-* 自定义数据

<view data-id="123" bindtap="handleDataTap">点击获取 data-id</view>
Page({
  handleDataTap(e) {
    const id = e.currentTarget.dataset.id; // 123
    console.log("data-id:", id);
  }
});

四、阻止事件冒泡(catch vs bind

  • bind:允许事件向上冒泡(父组件也会触发相同事件)。

  • catch:阻止事件冒泡(仅当前组件触发)。

示例

<view bindtap="parentTap">
  <view catchtap="childTap">点击我(不会触发父组件的 tap)</view>
</view>
Page({
  parentTap() {
    console.log("父组件点击"); // 不会执行(因为子组件用了 catchtap)
  },
  childTap() {
    console.log("子组件点击");
  }
});

五、自定义组件事件(triggerEvent

如果使用自定义组件,可以通过 triggerEvent 触发父组件的事件:

子组件

Component({
  methods: {
    handleTap() {
      this.triggerEvent("customevent", { data: "Hello" });
    }
  }
});

父组件

<child bindcustomevent="handleCustomEvent" />
Page({
  handleCustomEvent(e) {
    console.log("自定义事件数据:", e.detail.data); // "Hello"
  }
});

六、总结

场景推荐写法
普通点击事件bindtap="handleTap"
阻止冒泡catchtap="handleTap"
表单输入bindinput="handleInput"
表单提交bindsubmit="handleSubmit"
自定义组件通信triggerEvent + bind事件名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@程序员ALMJ

打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值