微信小程序开发内测一个月.数据传递的方式很少.经常遇到页面销毁后回传参数的问题,小程序中并没有类似Android的startActivityForResult的方法,也没有类似广播这样的通讯方式,更没有类似eventbus的轮子可用.
现在已知传递参数的方法只找到三种,先总结下.由于正处于内测阶段,文档也不是很稳定,经常修改,目前尚没有人造轮子.
先上GIF:
1.APP.js
我把常用且不会更改的参数放在APP.js的data里面了.在各个page中都可以拿到var app = getApp();
app上就可以拿到存在data中的参数.
2. wx.navigateTo({})中URL携带参数
demo中已经写出:
wx.navigateTo({
url: "../newpage/newpage?infofromindex=" + this.data.infofromindex,
});
3.wx.setStorage(OBJECT) 数据缓存
微信开发文档中的数据缓存方法:
①存储数据
try {
wx.setStorageSync(‘infofrominput‘, this.data.infofrominput)
} catch (e) {
}
②获取数据
//获取
wx.getStorage({
key: ‘infofrominput‘,
success: function (res) {
_this.setData({
infofromstorage: res.data,
})
}
})
key是本地缓存中的指定的 key,data是需要存储的内容.
详情见微信小程序开发文档:文档
贴上代码:
1.index.js
[javascript] view plain copy
- //index.js
- //获取应用实例
- var app = getApp()
- Page({
- data: {
- info: app.data.info,
- infofromindex: ‘来自index.js的信息‘,
- infofrominput: ‘‘
- },
- onLoad: function () {
- },
- //跳转到新页面
- gotonewpage: function () {
- wx.navigateTo({
- url: "../newpage/newpage?infofromindex=" + this.data.infofromindex,
- });
- },
- //获取输入值
- searchInputEvent: function (e) {
- console.log(e.detail.value)
- this.setData({ infofrominput: e.detail.value })
- },
- //保存参数
- saveinput: function () {
- try {
- wx.setStorageSync(‘infofrominput‘, this.data.infofrominput)
- } catch (e) {
- }
- }
- })
2.index.wxml
[html] view plain copy
- <!--index.wxml-->
- <view>
- <button style="background-color:#00ff00;margin:20rpx" bindtap="gotonewpage">跳转</button>
- <input style="background-color:#eee;margin:20rpx;height:80rpx" placeholder="请输入需要保存的参数" bindinput="searchInputEvent" />
- <button style="background-color:#ff0000;margin:20rpx" bindtap="saveinput">存入Storage</button>
- </view>
3.newpage.js
[javascript] view plain copy
- //newpage.js
- //获取应用实例
- var app = getApp()
- Page({
- data: {
- infofromapp: app.data.infofromapp,
- infofromindex: ‘‘,
- infofromstorage: ‘‘,
- },
- onLoad: function (options) {
- var _this = this;
- var infofromindex = options.infofromindex;
- this.setData({
- infofromindex: infofromindex
- })
- //获取
- wx.getStorage({
- key: ‘infofrominput‘,
- success: function (res) {
- _this.setData({
- infofromstorage: res.data,
- })
- }
- })
- }
- })
4.newpage.wxml
[html] view plain copy
- <!--newpage.wxml-->
- <view style="width:100%;margin:30rpx">infofromapp:{{infofromapp}}</view>
- <view style="width:100%;margin:30rpx">infofromindex:{{infofromindex}}</view>
- <view style="width:100%;margin:30rpx">infofromstorage:{{infofromstorage}}</view>
5.app.js
[javascript] view plain copy
- //app.js
- App({
- data: {
- infofromapp: ‘来自APP.js的信息‘
- },
- onLaunch: function () {
- }
- })