自己写了两个全局方法,用于解决页面间传递参数问题,包括A页面跳转到B页面,B页面返回A页面后更新A页面状态,或者A页面向B页面传递参数等
/** * this.radio对象数据结构 * { * name:{ * data,//可以是任意数据类型 * methods//一个数组,用于缓存回掉方法 * } * } *///接收数据receive(name, callBack) { //初始化存储对象 if (!this.radio) this.radio = {}; if (!this.radio[name]) this.radio[name] = {}; //如果存储对象指定name的对象中data存在,则直接执行回掉 if (this.radio[name].data) { callBack(this.radio[name].data); } else { if (!this.radio[name].methods) this.radio[name].methods = []; //否则添加到缓存队列中 this.radio[name].methods.push(callBack); }},//发送数据send(name, data) { if (!this.radio) this.radio = {}; if (!this.radio[name]) this.radio[name] = {}; //如果方法存在,则执行所有缓存的方法 if (this.radio[name].methods) { this.radio[name].methods.forEach((method) => { method(data); }) this.radio[name] = null; //清除 } else { this.radio[name].data = data; }}, |
将上述两个全局方法添加到app.js中,然后就可以使用了,使用方式如下
var app = getApp();//接收数据,需要传一个key,和一个回掉函数,app.receive('shan', (res) => {//res就是send传递的数据,这里是28 //获取数据后执行的代码})//发送数据,需要传一个key,和要发送的数据,这里发送的数据是一个数字28app.send('shan', 28); |
可以在A页面调用receive方法,预先写好回掉函数改变A页面状态,然后跳转到B页面调用send发送数据并返回,这时会执行回掉函数改变A页面的状态
采用发布订阅模式
其原理就是创建一个全局变量radio对象,通过send方法将指定名称的参数存储在radio中,调用receive方法后判断对应名称的参数是否存在,如果存在则直接执行回掉函数,如果不存在就将回掉函数存储在数组中,等待获取数据后执行
可能有问题,欢迎交流

感谢楼主提供的思路, 正为提交表单后, 列表页刷新头痛呢, 参照你的方法改了一下, 把问题解决了. 感谢!
测试中发现 send方法中的这条语句可能有问题:
this.radio[name] =null;//清除觉得应该是:this.radio[name].data =null;//清除这是放到globalData中了?
请问下大神 wx.setStorage缓存的数据 和 在app.js中设置的全局数据 , 这两个的生命周期都是一样的吗? 是否可以认为这两中数据缓存效果完全一致呢?
不一样,小程序退出后全局数据就没了,setStorage保存的数据是永久的,除非用户删除小程序