wx.navigateTo传值
保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。小程序中页面栈最多十层。
- 传参格式:参数与路径之间使用
?分隔,参数键与参数值用=相连,不同参数用&分隔;如
'/pages/index/index?value1=hello&value2=world'
-
不同类型的参数传递
Tip:其中下面的index是传值页面,text为接收参数页面
字符串
// index.js onClick: function (e) { var str = 'Hello World' wx.navigateTo({ url: '../test/test?str=' + str, success: function(res) {}, fail: function(res) {}, complete: function(res) {}, }) } // test.js onLoad: function(options) { var str = options.str this.setData({ str: str }) }Tips:
-
当传递的是布尔类型的话也会不变成字符串'true'/'false',通过var isTrue = (options.str == 'true') ? true : false 来设置
-
当传递的是整型,通过字符串转整型来处理:var index = parseInt(options.str)
-
对象/数组
通过JSON.stringify将对象转换为字符串传递,接收时需要通过JSON.parse将字符串转换为对象
// index.js
onClick: function (e) {
var obj = JSON.stringify(myObj) //myObj:本js文件中的对象
wx.navigateTo({
url: '../test/test?obj=' + obj,
success: function(res) {},
fail: function(res) {},
complete: function(res) {},
})
}
// test.js
onLoad: function(options) {
var obj =JSON.parse(options.obj)
// testObj:本js文件中的对象
this.setData({
testObj: obj
})
}
如果对象的参数或数组的元素中遇到地址,地址中包括?、&这些特殊符号时,对象/数组先要通过JSON.stringify转化为字符串再通过encodeURIComponent编码,接收时,先通过decodeURIComponent解码再通过JSON.parse转换为JSON格式的对象/数组
// index.js
onClick: function (e) {
var obj = JSON.stringify(myObj) //myObj:本js文件中的对象
wx.navigateTo({
url: '../test/test?obj=' + encodeURIComponent(obj), // 进行编码
success: function(res) {},
fail: function(res) {},
complete: function(res) {},
})
}
// test.js
onLoad: function(options) {
var obj =JSON.parse(decodeURIComponent(options.obj))
// testObj:本js文件中的对象
this.setData({
testObj: obj
})
}