uni-app navigateTo跳转页面使用encodeURIComponent(JSON.stringify(this.devObj))传递对象报错
uni-app navigateTo跳转页面使用encodeURIComponent(JSON.stringify(this.devObj))传递对象报错
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win10 | HBuilderX |
产品分类:uniapp/App
PC开发环境操作系统:Windows
PC开发环境操作系统版本号:win10
HBuilderX类型:正式
HBuilderX版本号:3.99
手机系统:Android
手机系统版本号:Android 13
手机厂商:vivo
手机机型:V1938T
页面类型:vue
vue版本:vue2
打包方式:云端
项目创建方式:HBuilderX
示例代码:
<template>
<view class="">
<button @tap="sendData">页面跳转传参按钮</button>
</view>
</template>
<script>
export default {
data() {
return {
// 传递的对象
devObj:{
Field1:'msg1',
Field2:'msg2%'
}
}
},
methods: {
sendData(){
uni.navigateTo({
url: `/pages/accetDataPage/accetDataPage?devObj=${encodeURIComponent(JSON.stringify(this.devObj))}`
})
}
}
}
</script>
<style>
</style>
操作步骤:
<template>
<view class="">
<button @tap="sendData">页面跳转传参按钮</button>
</view>
</template>
<script>
export default {
data() {
return {
// 传递的对象
devObj:{
Field1:'msg1',
Field2:'msg2%'
}
}
},
methods: {
sendData(){
uni.navigateTo({
url: `/pages/accetDataPage/accetDataPage?devObj=${encodeURIComponent(JSON.stringify(this.devObj))}`
})
}
}
}
</script>
<style>
</style>
预期结果:
- 不会报错
实际结果:
- 解析%存在问题
bug描述:
navigateTo跳转页面使用encodeURIComponent(JSON.stringify(this.devObj))
传递对象报错,此对象的信息只要含有%,新页面就会报"URIError: URI malformed"的错误
特殊符号需要转码
<template>
<view class="">
<button @tap=“sendData”>页面跳转传参按钮</button>
</view>
</template>
参考文档:https://blog.csdn.net/u010486124/article/details/81102224
在 uni-app
中使用 navigateTo
跳转页面时,如果通过 encodeURIComponent(JSON.stringify(this.devObj))
传递对象,可能会遇到以下问题:
-
URL 长度限制:URL 的长度是有限制的,如果传递的对象过大,可能会导致 URL 超出限制,从而报错。
-
特殊字符问题:即使使用了
encodeURIComponent
,某些特殊字符仍然可能会导致解析问题。 -
性能问题:将大对象编码为字符串并通过 URL 传递,可能会影响性能。
解决方案
1. 使用 uni.setStorageSync
和 uni.getStorageSync
可以将对象存储在本地存储中,然后在目标页面中读取。
传递对象:
uni.setStorageSync('devObj', this.devObj);
uni.navigateTo({
url: '/pages/targetPage/targetPage'
});
接收对象:
onLoad() {
const devObj = uni.getStorageSync('devObj');
console.log(devObj);
}
2. 使用 EventBus
或 Vuex
如果项目比较复杂,可以考虑使用 EventBus
或 Vuex
来管理全局状态。
使用 EventBus:
// 在发送页面
import EventBus from '@/utils/EventBus';
EventBus.$emit('devObj', this.devObj);
uni.navigateTo({
url: '/pages/targetPage/targetPage'
});
// 在接收页面
import EventBus from '@/utils/EventBus';
onLoad() {
EventBus.$on('devObj', (devObj) => {
console.log(devObj);
});
}
使用 Vuex:
// 在发送页面
this.$store.commit('setDevObj', this.devObj);
uni.navigateTo({
url: '/pages/targetPage/targetPage'
});
// 在接收页面
onLoad() {
const devObj = this.$store.state.devObj;
console.log(devObj);
}
3. 使用 URLSearchParams
传递少量数据
如果对象较小,可以将其拆分为多个参数传递。
传递对象:
const params = new URLSearchParams();
params.append('key1', this.devObj.key1);
params.append('key2', this.devObj.key2);
uni.navigateTo({
url: `/pages/targetPage/targetPage?${params.toString()}`
});
接收对象:
onLoad(options) {
const key1 = options.key1;
const key2 = options.key2;
console.log({ key1, key2 });
}