2019-06-13 13:27:17 177浏览
今天千锋扣丁学堂HTML5培训老师给大家分享一篇关于JavaScript微信小程序页面间跳转传参方式总结的详细介绍,首先在做微信小程序的时候,经常会遇到需要页面间传递参数的情况,根据目前项目经验,总结了以下几种方式:URL传参、缓存和方法调用。
// pageA.vue goToPageB() { let arg = { name: 'Jack', age: 9 } // 先把参数保存到缓存 比如这里用的是小程序的Storage,这里采用同步的方式 wx.setStorageSync({ key: 'pageArg', data: arg }) wx.navigateTo({ url: 'pageB' }) } // pageB.vue mounted() { // 从缓存中取出参数 let arg = wx.getStorageSync('pageArg') // 清除缓存中的页面参数 wx.removeStorageSync('pageArg') // 进行业务处理 // ... }
主要是用了小程序提供的getCurrentPages方法,具体内容可查看文档,我这里直接就贴图了,因为文档说的很简单
// 往前获取页面对象,类似history.go(-n) function getPageByPreCount(n) { let currentPages = getCurrentPages() return currentPages[Math.max(0, currentPages.length - (n + 1))] } /* 返回上一页并带回参数 * parameter functionName 上一个页面中用来接收带回参数的方法名称,注意:方法要在data中 * parameter args 带回去的参数 */ function returnPrevPage(functionName, ...args) { if (functionName) { let prevPage = getPageByPreCount(1) wx.navigateBack() // 方法里手动调用了页面的方法,并把页面参数在这里作为方法参数传递 prevPage.data.$root[0] && typeof prevPage.data.$root[0][functionName] == 'function' && prevPage.data.$root[0][functionName](...args) } else { wx.navigateBack() } }
// user-pick.vue methods: { onSelectConfirm(users) { returnPrevPaeg('onSelectUser', users) } } // user-pick.vue data() { return { // 把具体处理还是放到了methods中,如果处理逻辑比较简单也可以直接放这里 onSelectUser: this.onUserOk } }, methods: { onUserOk(users) { // 拿到用户信息 进行搜索操作 // this.search(user) } }
// 前进页面回调方法 function navigateTo (url,functionName,...args) { triggerNextPageFn('onHide', functionName, ...args) // 跳转后处理数据 wx.navigateTo({url}) } function redirectTo (url,functionName,...args) { triggerNextPageFn('onUnload', functionName, ...args) // 跳转后处理数据 wx.redirectTo({url}) } // 通用触发后一个页面的方法 function triggerNextPageFn(type, functionName, ...args) { let prePage = getCurPage() if (functionName) { // 保存当前变量 ((..._args) => { let oldEventFn = prePage[type] prePage[type] = () => { // 前进页面改变onReady方法,这里使用了setTimeout setTimeout(() => { let newPage = getCurPage() let oldOnReady = newPage.onReady newPage.onReady = function () { newPage.data.$root[0] && typeof newPage.data.$root[0][functionName] == 'function' && newPage.data.$root[0][functionName](..._args) oldOnReady.apply(newPage) newPage.onReady = oldOnReady } }) prePage[type] = oldEventFn } })(...args) } }
【关注微信公众号获取更多学习资料】 【扫码进入HTML5前端开发VIP免费公开课】