微信小程序传参过长被截断,看过来!

一、encodeURIComponent 和 decodeURIComponent

问题一: 网上说的 navigateTo 进行传参的时候因为数据过长被截断了,其实微信传参的数据长度能达到45kb左右,几乎可以传递工作中所有的数据了。

其实是链接里有特殊字符

比如这个链接: mp.weixin.qq.com/s?__biz=MzA…

正常传参会被截断,因为含有特殊字符问号

image.png

解决办法

1、采用encodeURIComponent把拼接的参数编码之后,拼接在链接上,在接受的页面的onLoad生命周期,接收到参数之后,采用decodeURIComponent进行解码后就能正常的使用。

let test =  https://mp.weixin.qq.com/s?__biz=MzA4MTQ2NDg1NQ==&mid=504984964&idx=1&sn=b9fc08b796f91ec296ec5e25feb6cf6c&chksm=04794efc330ec7ea6dbd40d9e16326e24d05a30e55eaad1af1c96e2d6514658cae5366d2dbd#rd
wx.navigateTo({
  url: '、/pages/index/index?obj=encodeURIComponent(test)'
})



// 解码

 onLoad: function(option){
   let { obj } = option || {};
   obj = decodeURIComponen(obj);
   // 接下来正常使用就行
 }

复制代码

二、eventChannel

1、采用微信官方提供的通信方法,eventChannel,和被打开页面进行通信。

下面看一个官方的链接你就懂了:

  • 当期页面
wx.navigateTo({
  url: 'test?id=1',
  events: {
    // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
    ...
  },
  success: function(res) {
    // 通过eventChannel向被打开页面传送数据
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
  }
})
复制代码
  • 接收页面
//test.js
Page({
  onLoad: function(option){
    console.log(option.query)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
    eventChannel.emit('someEvent', {data: 'test'});
    // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function(data) {
      console.log(data)
    })
  }
})
复制代码

官方链接戳这里!

总结:

不建议把过多的参数通过参数传过去,如果数据参数过多,尽量通过id,然后在跳转的页面进行接口查询。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享