6人参与 • 2025-04-24 • Javascript
微信小程序使用 bind
或 catch
前缀绑定事件,语法如下:
<组件 bind事件名="处理函数" catch事件名="处理函数"></组件>
bind
:事件绑定,允许事件冒泡(向父组件传递)。catch
:事件绑定,阻止事件冒泡(不会向父组件传递)。事件名 | 说明 | 适用组件 |
---|---|---|
tap | 点击事件 | view , button |
input | 输入框内容变化 | input , textarea |
submit | 表单提交 | form |
scroll | 滚动事件 | scroll-view |
longpress | 长按事件(350ms) | view , button |
<!-- 点击事件(允许冒泡) --> <view bindtap="handletap">点击我</view> <!-- 阻止冒泡 --> <view catchtap="handlenobubbletap">点击我(不冒泡)</view>
page({ handletap() { console.log("点击事件触发"); }, handlenobubbletap() { console.log("点击事件触发,但不会冒泡"); } });
<input bindinput="handleinput" placeholder="输入内容" />
page({ handleinput(e) { console.log("输入内容:", e.detail.value); } });
<form bindsubmit="handlesubmit"> <input name="username" placeholder="用户名" /> <button form-type="submit">提交</button> </form>
page({ handlesubmit(e) { console.log("表单数据:", e.detail.value); } });
事件处理函数的参数 event
包含以下关键属性:
属性 | 说明 |
---|---|
type | 事件类型(如 tap , input ) |
target | 触发事件的组件(原始事件源) |
currenttarget | 当前绑定事件的组件 |
detail | 额外信息(如输入框的值) |
timestamp | 事件触发时间戳 |
touches | 触摸点信息(多指触控) |
<view data-id="123" bindtap="handledatatap">点击获取 data-id</view>
page({ handledatatap(e) { const id = e.currenttarget.dataset.id; // 123 console.log("data-id:", id); } });
bind
:允许事件向上冒泡(父组件也会触发相同事件)。catch
:阻止事件冒泡(仅当前组件触发)。示例
<view bindtap="parenttap"> <view catchtap="childtap">点击我(不会触发父组件的 tap)</view> </view>
page({ parenttap() { console.log("父组件点击"); // 不会执行(因为子组件用了 catchtap) }, childtap() { console.log("子组件点击"); } });
如果使用自定义组件,可以通过 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事件名 |
到此这篇关于微信小程序事件绑定基本语法的文章就介绍到这了,更多相关微信小程序事件绑定基本语法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论