“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 27 天,点击查看活动详情”
事件传参与数据同步
1.在事件处理函数中为data中的数据赋值
通过调用**this.setData(dataObject)**方法,可以给页面data中的数据重新赋值,示例如下:
想要实现的效果是,点击按钮,下面的数字会依次加1
index.wxml
<!--index.wxml-->
<!-- <view class="container">
<view class="userinfo">
<block wx:if="{{canIUseOpenData}}">
<view class="userinfo-avatar" bindtap="bindViewTap">
<open-data type="userAvatarUrl"></open-data>
</view>
<open-data type="userNickName"></open-data>
</block>
<block wx:elif="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:elif="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
<view wx:else> 请使用1.4.4及以上版本基础库 </view>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<view class="usermotto">
<text class="user-motto">{{motto}}</text>
</view>
</view> -->
<button type="primary" bindtap="btnTapHander">按钮</button>
<button type="primary" bindtap="CountChange">+1</button>
index.js
// index.js
// 获取应用实例
// const app = getApp()
// Page({
// data: {
// motto: 'Hello World',
// userInfo: {},
// hasUserInfo: false,
// canIUse: wx.canIUse('button.open-type.getUserInfo'),
// canIUseGetUserProfile: false,
// canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
// },
// // 事件处理函数
// bindViewTap() {
// wx.navigateTo({
// url: '../logs/logs'
// })
// },
// onLoad() {
// if (wx.getUserProfile) {
// this.setData({
// canIUseGetUserProfile: true
// })
// }
// },
// getUserProfile(e) {
// // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
// wx.getUserProfile({
// desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
// success: (res) => {
// console.log(res)
// this.setData({
// userInfo: res.userInfo,
// hasUserInfo: true
// })
// }
// })
// },
// getUserInfo(e) {
// // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
// console.log(e)
// this.setData({
// userInfo: e.detail.userInfo,
// hasUserInfo: true
// })
// }
// })
Page({
data:{
info: 'heollo world',
randomNum1: Math.random()*10,
randomNum2: Math.random().toFixed(2),
count: 0
},
btnTapHander(e) {
console.log(e)
},
CountChange(e){
this.setData({
count: this.data.count+1
})
}
})
核心代码:
主要函数:
初始时:
点击此按钮,count的值每次加1:
2.事件传参
小程序中的事件传参比较特殊,不能在绑定事件的同时为事件处理函数传递参数。常工作:
因为小程序会把 bindtap的属性值,统一当作事件名称来处理,相当于要调用一个名称为btnHandler(123)的事件处理函数。
“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 27 天,点击查看活动详情”