Technology Sharing

Data Communication in WeChat Mini Programs

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Method 1: Using a callback function

  • In app.js: You can modifyglobalDataA callback function is executed after that. This callback function can be an update function passed by the page to the app.
    1. // app.js
    2. App({
    3. globalData: {
    4. someData: '',
    5. },
    6. setSomeData(newData, callback) {
    7. this.globalData.someData = newData;
    8. if (typeof callback === 'function') {
    9. callback();
    10. }
    11. },
    12. })

    In the subpage: Call where neededappInstance.setSomeDataAnd pass a callback function

    1. // pages/index/index.js
    2. Page({
    3. onLoad() {
    4. const appInstance = getApp();
    5. appInstance.setSomeData('new value', () => {
    6. this.setData({
    7. localData: appInstance.globalData.someData,
    8. });
    9. });
    10. },
    11. })

    Method 2: Using an event bus

    Create an event bus (EventBus)app.jsTrigger an event in the subpage and listen to this event in the subpage.

  • Event Bus (bus.js)