Error in onLoad hook: “URIError: URI malformed“ found in…报错处理以及完善uniapp针对对象传参

  • 使用uniapp传参的过程中遇到这么一个问题,当我们需要传整个对象作为参数时,我会先将这个对象先编码,然后再解码,从而获取到怎么参数,平常实操的时候也没有遇到过问题,但是今天测试的时候,刚好一个数据碰巧,就报错了,报错内容就是:

Error in onLoad hook: “URIError: URI malformed“ found in

 原来uniapp针对对象传参编码(encodeURIComponent)和解码(decodeURIComponent)如下:

//跳转前页面的方法
toDeviceDetail(deviceInfo) {
    //传参对象,使用encodeURIComponent编码
    let query = encodeURIComponent(JSON.stringify(deviceInfo))
	uni.navigateTo({
		url:'/pages/……/deviceDetail?deviceQuery='+ query
	})
},


// 跳转后页面获取的参数的方法
onLoad(options) {
    let obg ={}
    // 获取传递的对象参数,使用decodeURIComponent解码,并转为对象
    obj = JSON.parse(decodeURIComponent(options.deviceQuery));
}
  • 今天发现的这个bug是,如果编码的对象中的参数有“%”,那么就会对编码跟解码造成问题,从而报错
  • 解决方案:正常解码,编码时对所有“%”进行单独处理,手动转换为“%25”,代码如下:
toDeviceDetail(deviceInfo) {
    //传参对象,使用encodeURIComponent编码
    let str = JSON.stringify(deviceInfo)
    //注意这里——————————————————————
    str = str.replace(/%/g, '%25')
    //这里———————————————————————————
    let query = encodeURIComponent(JSON.stringify(deviceInfo))
	uni.navigateTo({
		url:'/pages/……/deviceDetail?deviceQuery='+ query
	})
},
  • 最终实现在uni-app中跳转页面并传递对象参数的需求

猜你喜欢

转载自blog.csdn.net/qq_45796592/article/details/131162270