小程序模板中怎么传递参数?

小程序模板中怎么传递参数,在JS文件中因为有其他地方传递了type所以方法这边改不了,模板中不能直接传递参数吗?查了文档说可以用data-type,那方法那边接参应该怎么写呢?谢谢

<view catch:tap="saveInfo(2)">保存</view>

saveInfo(type) { ... }

小程序模板中怎么传递参数?

阅读 901
avatarAI BotBETA

在微信小程序中,你可以通过在模板中设置属性(data- 开头的属性)来传递参数。在你的例子中,如果你想通过 catch:tap 事件传递参数,你可以这样做:

<view catch:tap="saveInfo" data-type="2">保存</view>

然后在你的 saveInfo 方法中,你可以通过 event.dataset 来获取这个参数:

saveInfo(event) {
  let type = event.dataset.type;
  // 你的其他代码...
}

这样,当用户点击这个视图时,saveInfo 方法就会被调用,并且 type 参数就会是 "2"。

请注意,这种传递参数的方式只适用于在模板中触发的事件。如果你想在页面加载时传递参数,你应该使用 data 属性。例如:

<view data-type="2">保存</view>

然后在你的 Page 对象中,你可以通过 this.data 来获取这个参数:

Page({
  data: {
    type: '',
  },
  onLoad: function() {
    let type = this.data.type;
    // 你的其他代码...
  }
})
2 个回答
<view data-id="1" tap="saveInfo()">保存</view>


saveInfo: function (e) {
    let id = e.target.dataset.id
    console.log("id:"+id);
  },


小程序事件传参不是在函数中直接传参,而是通过标签属性传入参数,我在这里举个例子:
比如你要通过id查询详情:

<view bindtap="getDetail" data-id="{{ item.id }}">获取详情</view>

在函数中获取参数:

getDetail(val){
  let { id } = val.currentTarget.dataset;
  // id
},

这里的data-idid就是你携带的key{{ item.id }}就是你传入的参数

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题