微信页面传值

微信好像没有类似iOS 中的block回传页面的值。如果有的话,希望告知。

1 . 用 navigator标签传值或 wx.navigator, 比如A->B 页面,在B页面的 onload方法内接受值。

//A页面
clickAd:function (e) {
    wx.navigateTo({
      url: '/pages/makeorder/makeorder?title=你好',
      success:function(){

      },
      fail:function(){

      },
      complete:function(){

      }
    })
  }
//B页面接收值
/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      wx.showModal({
        title: '收到的值',
        content: options.title,
        confirmText:'知道了',
        cancelText:'好的',
        success:function(res){
          console.log(res);
        }
      })
      wx.setNavigationBarTitle({
        title: '订单',
      })
  },

如果需要传多个参数, 用 & 链接即可

如果要传 数组, 字典等复杂类型, 要先用 JSON.stringify() 转成字符串传递.
注 : 如果转化的字符串中 有”?”这个符号, 则只会传递”?”以前的字符串, 这个问题我猜想可能是小程序内部的路由处理 对这个”?”敏感吧
好, 这是第一种 依靠跳转的url带参数传值

2 .网上有人说用 用getCurrentPages(); 获取栈中全部页面的, 然后把数据写入相应页面 ,但是我经过测试,发现onShow 的执行在 success 之前,虽然对结果没有什么影响,但是我觉得这种顺序跟我想的调用不一样。

3 . 写入本地, 跨页面在取出来 wx.setStorage/wx.getStorage等, 小程序中对写入本地数据 封装了很多方法, 各有侧重, 这里就不多说了

A页面
onShow:function(){
    var location = wx.getStorageSync('location');
    if (location) {
      this.setData({
        location:location
      })
    }
  }
B页面
 wx.setStorageSync('location','北京');
    wx.navigateBack({
      delta: 1,
      success:function(res){

      }
    })

4 . 把 数据声明为全局变量
var detail = getApp().detail; 可在任何页面获取

app.js
 globalData:{
      city:'北京',
  },
A页面
onShow:function() {
    var location = getApp().globalData.city;
    if (location){
      this.setData({
          location:location
      })
    } 
  }

B页面
    getApp().globalData.city = '上海';

猜你喜欢

转载自blog.csdn.net/wangqiuwei07/article/details/80973524
今日推荐