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

一.全局数据共享

声明全局的变量,在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})
  }

})
相关推荐
计算机毕设指导6几秒前
基于微信小程序的个性化漫画阅读推荐系统【源码文末联系】
java·python·微信小程序·小程序·tomcat·maven·intellij-idea
百锦再几秒前
开发抖音小程序组件大全概述
人工智能·python·ai·小程序·aigc·notepad++·自然语言
Lucky小黄人12 小时前
微信小程序开发常见报错
微信小程序·小程序
Stanford_110621 小时前
【2026新年启程】学习之路,探索之路,技术之路,成长之路……都与你同行!!!
前端·c++·学习·微信小程序·排序算法·微信开放平台
初学者52131 天前
微信小程序调用录音没反应,本地开发测试却没问题,operateRecorderfail appid privacy api banned
微信小程序·小程序
微爱帮监所写信寄信1 天前
微爱帮监狱寄信写信小程序信件内容实时保存技术方案
java·服务器·开发语言·前端·小程序
说私域1 天前
基于开源AI大模型AI智能名片S2B2C商城小程序的内容价值生成与多点选择传播策略研究
人工智能·微信·小程序·开源
2501_916007472 天前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
iOS 抓包工具有哪些?不同类型的抓包工具可以做什么
android·ios·小程序·https·uni-app·iphone·webview