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

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

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

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

常见事件类型

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

二、事件绑定示例

1. 点击事件(bindtap / catchtap


点击我


点击我(不冒泡)
Page({
  handleTap() {
    console.log("点击事件触发");
  },
  handleNoBubbleTap() {
    console.log("点击事件触发,但不会冒泡");
  }
});

2. 输入事件(bindinput

Page({
  handleInput(e) {
    console.log("输入内容:", e.detail.value);
  }
});

3. 表单提交(bindsubmit

Page({
  handleSubmit(e) {
    console.log("表单数据:", e.detail.value);
  }
});

三、事件对象(event

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

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

获取 data-* 自定义数据

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

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

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

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

示例


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

五、自定义组件事件(triggerEvent

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

子组件

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

父组件

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

六、总结

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

你可能感兴趣的:(微信小程序,小程序)