
目录
事件传参:在触发事件时,将一些数据作为参数传递给事件处理函数的过程,就是事件传参。
在微信小程序中,我们经常会在组件上添加一些自定义数据,然后在事件处理函数中获取这些自定义数据,从而完成业务逻辑的开发。
上一章我们了解到,在组件上通过data-"的方式定义需要传递的数据,其中*是自定义的属性,例如: <view data-id="100" bindtap="handier"/>然后通过事件对象进行获取自定义数据。
本章我们讲解另一种方法,小程序进行事件传参的时候,除了使用 data-* 属性传递参数外,还可以使用 mark 标记传递参数mark是一种自定义属性,可以在组件上添加,用于来识别具体触发事件的target节点。
同时mark还可以用于承载一些自定义数据在组件上使用 mark:自定义属性 的方式将数据传递给事件处理函数。
例如: <view mark:id="100" bindtap="handler"/>然后通过事件对象进行获取自定义数据
步骤一:按钮的创建
找到购物车页面,找到其文件路径,快速找到cart.wxml文件,编写代码,创建一个按钮:
<view>
<button>按钮</button>
</view>

步骤二:按钮属性配置
找打上一配置的cate.scss文件将其中的内容复制粘贴到cart.scss文件中,配置按钮相关属性:
view{
display: flex;
height: 300rpx;
background-color: skyblue;
align-items: center;
}

步骤三:添加点击事件
在cart.wxml文件中创建一个名为"bluHandler"的点击事件:
<view>
<button bind:tap="btuHandler">按钮</button>
</view>

步骤四:参数传递
如果需要使用 mark 进行事件传参,如果需要使用 mark:自定义属性的方式进行参数传递:
<view>
<!-- 如果需要使用 mark 进行事件传参,如果需要使用 mark:自定义属性的方式进行参数传递 -->
<button bind:tap="btuHandler" mark:id="1" mark:name="tom">按钮</button>
</view>

步骤五:打印数据
找到cart.js文件,对按钮绑定事件进行处理:
Page({
// 按钮绑定的事件处理函数
btuHandler(event){
console.log(event)
}
})


步骤六:获取数据
Page({
// 按钮绑定的事件处理函数
btuHandler(event){
console.log(event.mark.id)
console.log(event.mark.name)
}
})

步骤七:父进程验证
找到cart.wxml对view添加事件:
<view bind:tap="parentHandler" mark:parentid="1" mark:parentname="tom">
<!-- 如果需要使用 mark 进行事件传参,如果需要使用 mark:自定义属性的方式进行参数传递 -->
<!-- <button bind:tap="btuHandler" mark:id="1" mark:name="tom">按钮</button> -->
<button mark:id="1" mark:name="tom">按钮</button>
</view>

在找到cart.js文件,对view创建的事件,读取:
首先点击蓝色区域(不点击按钮):
Page({
// 按钮绑定的事件处理函数
btuHandler(event){
console.log(event.mark.id)
console.log(event.mark.name)
},
//view 绑定的事件处理函数
parentHandler(event){
//先点击蓝色区域
// 通过事件对象获取的是 view 身上绑定的数据
console.log(event)
}
})

点击按钮(不点击蓝色区域):
Page({
// 按钮绑定的事件处理函数
btuHandler(event){
console.log(event.mark.id)
console.log(event.mark.name)
},
//view 绑定的事件处理函数
parentHandler(event){
//先点击蓝色区域
// 通过事件对象获取的是 view 身上绑定的数据
// 先点击按钮(不点击蓝色区域)
console.log(event)
}
})

总结:data-*自定义数据和mark-自定义数据的区别
对于 data-*自定义数据:
点击蓝色区域(不点击按钮)
currentTarget 事件绑定者:view
target 事件触发者:view
不点击蓝色区域(点击按钮)
currentTarget 事件绑定者:view
target 事件触发者:按钮
如果想获取 view 身上的数据,就必须使用 currentTarget 才可以。
如果想获取的是时间触发者本身数据,就需要使用 target。
对于 mark-自定义数据:点击蓝色区域(不点击按钮)
通过事件对象获取的是 view 身上绑定的数据
不点击蓝色区域(点击按钮)
通过事件对象获取到的是 触发事件的节点 以及父节点身上的所有 mark 数据

