微信小程序 bindtap 事件多参数传递的代码示例
微信小程序 bindtap 事件多参数传递
在微信小程序中,我们无法直接通过 bindtap="handleClick(1,2,3)"
的方式传递参数,而是需要通过自定义属性 data-
的方式进行传递,并在事件回调函数中通过 event.currentTarget.dataset
来获取这些参数。然而,这种传参方式不够友好,尤其是在传递多个参数时,需要特别注意参数的形式和命名方式。
代码示例
index.wxml
<template name="like"> <view class="like-line"></view> <view class="like-wrap"> <view class="like {{ item.feedbackType === 1 ? 'selected' : '' }}" bindtap="like" data-args="{{ {item, index, type: 1} }}"> <!-- 👍--> </view> <view class="dislike {{ item.feedbackType === 2 ? 'selected' : '' }}" bindtap="like" data-args="{{ {item, index, type: 2} }}"> <!-- 👎--> </view> </view> </template>
index.js
Page({ async like(e) { let { item, type, index } = e.currentTarget.dataset['args'] let { feedbackType, recordId } = item console.log({ type, index, feedbackType, recordId }) // do something }, })
注意:
- 自定义属性命名,不能包含大写字母,大写会自动转成小写,可能会导致获取不到参数。如
data-recordId
会自动转成data-recordid
; - 如果使用
data-record-id
的形式,最终在 event.target.dataset 中会将-
转成驼峰的形式,即recordId
,取值需要用event.target.dataset['recordId']
。
微信小程序点击事件(bindtap)传递参数
小程序在组件上绑定事件后,传递参数的方式不同于前端开发其他场景中直接加参数的方式,小程序在参数的传递时,采用事件对象的自定义属性的方式,具体实现如下:
wxml:
<view bindtap="goTo" data-index="{{item.index}}">点击事件传参</view>
js中:
goTo: function(e){ // 传递的参数 const index= e.currentTarget.dataset['index']; }
利用自定义属性完成事件的参数传递
注意!!data-index
传参命名最好是小写,写成大写编译会转为小写的!!!获取还是得写小写来获取
到此这篇关于微信小程序 bindtap 事件多参数传递的文章就介绍到这了,更多相关微信小程序 bindtap 多参数传递内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Bootstrap基本插件学习笔记之Alert警告框(20)
这篇文章主要为大家详细介绍了Bootstrap基本插件学习笔记之ALert警告框的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-12-12js中的window.open返回object的错误的解决方法
系统中用javascript中的window.open后,页面返回了一个[object]。因为系统的原因,必需使用href="javascript:window.open()"这样的格式。所以只能通过以下办法解决。2009-08-08
最新评论