微信小程序-全局数据共享/页面间通信

一.全局数据共享

声明全局的变量,在app.js文件里

复制代码
App({

  //全局共享的数据
  globalData:{
    token:''
  },

  //设置全局数据
  setToken(token){
    this.globalData.token=token
  }


})

使用 getApp() 获取全局App实例

复制代码
//返回全局唯一的APP实例
const appInstance=getApp()

Page({

  login(){
    console.log(appInstance)
    appInstance.setToken('11111')
  }

})

二.页面间通信

上级页面使用回调函数参数eventChannel的emit方法发送数据给下级页面

使用events对象处理下级页面返回的数据

复制代码
Page({
  //点击按钮触发事件处理函数
  handler(){
    wx.navigateTo({
      url: '/pages/list/list',
      events:{
        //key:被打开页面的发射的事件
        //value:回调函数
        currentEvent:(res)=>{
          console.log(res)
        }
      },
      success(res){
        //通过回调函数获取eventChannel并发射数据
        res.eventChannel.emit('myevent',{
          name:'tom'
        })
      }
    })
  }
})

下级页面使用eventChanel的on方法监听发送的数据,使用emit方法发送数据给上级页面

复制代码
Page({
  onLoad(){
    //获取eventChannel事件
    const eventChanel = this.getOpenerEventChannel()

    //监听发射的事件
    eventChanel.on('myevent',(res)=>{
      console.log(res)
    })

    //也可以发数据
    eventChanel.emit("currentEvent",{age:10})
  }

})
相关推荐
2501_9160074714 小时前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063214 小时前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063218 小时前
iOS 抓包工具有哪些?不同类型的抓包工具可以做什么
android·ios·小程序·https·uni-app·iphone·webview
云起SAAS18 小时前
供求求购供应发布VIP会员抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·供求求购供应发布
毕设源码-朱学姐19 小时前
【开题答辩全过程】以 基于微信小程序旅游疫情防控管理系统为例,包含答辩的问题和答案
微信小程序·小程序·旅游
weixin_lynhgworld19 小时前
陪诊小程序系统开发:开启就医陪伴新体验 [特殊字符]
小程序
weixin_lynhgworld19 小时前
旧物回收小程序:让闲置物品焕发新生 ✨
java·开发语言·小程序
一点晖光21 小时前
ios底部按钮被挡住
前端·ios·微信小程序
前端程序猿之路1 天前
基于扣子(Coze)工作流 API 的微信小程序开发实践总结
前端·微信小程序·小程序·大模型·api·ai编程·扣子
德育处主任1 天前
在小程序做海报的话,Painter就很给力
前端·微信小程序·canvas