您的位置:首页 > 移动开发 > 微信开发

微信小程序实现页面跳转传值以及获取值的方法分析

2017-12-18 10:28 1356 查看

本文实例讲述了微信小程序实现页面跳转传值以及获取值的方法。分享给大家供大家参考,具体如下:

在安卓中页面跳转传值都是通过bundle,现在研究一下小程序的列表跳转及页面传值。

my.wxml

<view class="container">
<view bindtap="bindViewTap" class="userinfo">
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</view>
<view class="info_list">
<block wx:for="{{userListInfo}}" >
<view class="weui_cell" data-index="{{item.index}}" id="{{item.index}}"
bindtap="userinfo_item">
<view class="weui_cell_hd">
<image src="{{item.icon}}"></image>
</view>
<view class="weui_cell_bd">
<view class="weui_cell_bd_p"> {{item.text}} </view>
</view>
<view wx:if="{{item.isunread}}" class="badge">{{item.unreadNum}}</view>
<view class="with_arrow"></view>
</view>
</block>
</view>
</view>

my.js

var app = getApp()
Page({
data: {
userInfo: {},
userListInfo: [{
icon: '../../images/iconfont-dingdan.png',
text: '我的订单',
isunread: true,
unreadNum: 2,
index:1
}, {
icon: '../../images/iconfont-kefu.png',
text: '联系客服',
index: 5
}, {
icon: '../../images/iconfont-help.png',
text: '常见问题',
index: 6
}]
},
onLoad: function () {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function (userInfo) {
//更新数据
that.setData({
userInfo: userInfo
})
})
},
userinfo_item: function (e) {
var index = e.target.dataset.index;
console.log("----index----" + index)
console.log('-----id-----'
+ e.currentTarget.id)
var app = getApp();
//设置全局的请求访问传递的参数
app.requestId = e.currentTarget.id;
app.requestIndex = index;
}
})

微信小程序设置id的方法标识来传值

在要跳转的item处,设置一个id并给当前的id赋值上对应的key值,

id="{{item.index}}"

后我们在js的bindtap的响应事件中获取,并传递到下一个界面中;
获取到id传的值
通过
e.currentTarget.id;
获取设置的id值,并通过设置全局对象的方式来传递数值,
获取全局对象
var app=getApp();
//设置全局的请求访问传递的参数
app.requestDetailid=id;

在调试模式下:我们也可以在,wxml中查看到我们设置的每一个item的id值

通过使用data - xxxx 的方法标识来传值

通过使用data - xxxx 的方法标识来传值,xxxx可以自定义取名 比my.wxml中的data-index。
如何获取data-xxxx传递的值?
在js的bindtap的响应事件中:
通过数据解析一层层找到数据,

var id=e.target.dataset.index
(根据你的data-id的取名)
如js中的两个打印就是通过两种不同方式获得的id。

微信小程序如何跨页面获取值

依据上面的方式设置要传递的值,页面跳转后,我们就需要在下一个页面拿到传递的数据(这个数据在传递前,就已经被设置成全局变量)相当于给全局变量添加了新的key,value
在跳转后的js页面,接收传递过来的数据detail.js
同样通过全局额方式取值出来,(即和app.js中取某个变量的值是一样的)

var id=getApp().requestId;
var index=getApp().requestIndex;
console.log(id);
console.log(index);

通过链接传参:

wx.navigateTo({
url: '/pages/account/feedback/feedback?test=feedback_test&name=jia',
success: function(res) {},
fail: function(res) {},
complete: function(res) {},
})

点击页面跳转时通过?方式传参。在跳转后的页面JS中做如下接收:

onLoad: function (e) {
var movieid = getApp().requestId;
var movieIndex = getApp().requestIndex;
console.log("-----feedback--movieid--" + movieid +" " + movieIndex);
console.log("-----feedback--test--" + e.test);
console.log("-----feedback--name--" + e.name);
},

感觉比较好的方法还是通过链接方式进行参数传递,第一种有些像安卓中进行页面跳转,把一些传递的参数写到Application中,第二种是像通过bundle方式进行传递。前端小白总结,希望前端丰富的同学可以提供更多思路。

希望本文所述对大家微信小程序开发有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息