微信小程序--传值

1.使用wx.navigateTo指令在页面间传递数组元素

  • 页面之间传值,数据类型应为字符串类型,因此先将数组元素转化为字符串,到下一个页面再将其从字符串转化为数组。
//page1.js
//其中a是一个数组
var a = JSON.stringify(a)
//page2.js
//在onLoad中转化为数组
var a = JSON.parse(options.a)

其中url的形式为:

wx:navigateTo{
    url:\'xxx?a=\'+a\'&b=\'+b
}
  • 当传递的url中包含?;/等分隔符号时,传输的url被截断,这时要用到encodeURIComponent()decodeURIComponent()

encodeURIComponent()讲解链接:http://www.w3school.com.cn/jsref/jsref_encodeURIComponent.asp

decodeURIComponent()讲解链接:http://www.w3school.com.cn/jsref/jsref_decodeURIComponent.asp

传输端:

    wx:navigateTo({

      url=\'../../web/web?sub_url=\'+encodeURIComponent(sub_url),

    })

接收端:

    onLoad: function(options){

      var sub_url = decodeURIComponent(options.sub_url)

    }

注意!!!这两个函数的参数都必须为字符串

2.在wxml中使用非数组元素

wxml中view数据只能为数组类型,因此对于非数组元素,先将其转化为数组再使用。

//page.js
//a为数组,b为非数组数据
//方法1 var a = new Array() that.setData({ \'a[0]\':b, })
//方法2
that.setData({
a:[b],
})
//page.wxml
<view wx:for=\'{{a}}\'></view>

注意!!数据b有时看起来很像数组,但并非数组,不同网页间传输的数据一定不是数组类型,因此在wxml中使用data数据时一定要注意转换类型