微信小程序使用 bind
或 catch
前缀绑定事件,语法如下:
<组件 bind事件名="处理函数" catch事件名="处理函数"></组件>
-
bind
:事件绑定,允许事件冒泡(向父组件传递)。 -
catch
:事件绑定,阻止事件冒泡(不会向父组件传递)。
常见事件类型
事件名 | 说明 | 适用组件 |
---|---|---|
tap | 点击事件 | view , button |
input | 输入框内容变化 | input , textarea |
submit | 表单提交 | form |
scroll | 滚动事件 | scroll-view |
longpress | 长按事件(350ms) | view , button |
二、事件绑定示例
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 | 事件类型(如 tap , input ) |
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事件名 |