微信小程序中,当按钮点击后实现页面跳转与数据传递,主要涉及到以下步骤:
1. 创建新页面
首先,你需要创建一个新页面,比如叫做 newPage。
2. 定义按钮的点击事件
在当前页面(比如 currentPage)的 WXML 文件中,你需要在按钮元素上绑定一个 tap 事件。
<button bindtap="toNewPage">跳转到新页面</button>
3. 在页面的 JS 文件中定义处理函数
在 currentPage 的 JS 文件中,定义 toNewPage 函数。
Page({
toNewPage: function() {
// 页面跳转,传递参数
wx.navigateTo({
url: '/pages/newPage/newPage?param1=value1¶m2=value2',
});
}
});
这里,url 是跳转到的页面路径,? 后面是传递给新页面的参数,param1=value1 和 param2=value2 是你可以传递的任意键值对。
4. 接收并处理传递的数据
在 newPage 页面的 JS 文件中,你可以在 onLoad 函数中获取传递的数据。
Page({
onLoad: function(options) {
// options 参数中包含了传递的数据
console.log(options.param1); // 输出: value1
console.log(options.param2); // 输出: value2
}
});
5. 显示传递的数据
在新页面的 WXML 文件中,你可以使用 {{}} 来显示从上一个页面传递过来的数据。
<text>{{ param1 }}</text>
<text>{{ param2 }}</text>
完整示例
下面是一个完整的示例:
currentPage.wxml
<button bindtap="toNewPage">跳转到新页面</button>
currentPage.js
Page({
toNewPage: function() {
wx.navigateTo({
url: '/pages/newPage/newPage?param1=value1¶m2=value2',
});
}
});
newPage.wxml
<text>{{ param1 }}</text>
<text>{{ param2 }}</text>
newPage.js
Page({
onLoad: function(options) {
console.log(options.param1); // 输出: value1
console.log(options.param2); // 输出: value2
}
});
这样,当你点击按钮时,就会跳转到 newPage,并且能够显示从 currentPage 传递过来的数据。