微信小程序使用 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事件名 |
到此这篇关于微信小程序事件绑定基本语法的文章就介绍到这了,更多相关微信小程序事件绑定基本语法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论