Home  >  Article  >  WeChat Applet  >  A brief discussion on several ways of cross-page communication between mini programs

A brief discussion on several ways of cross-page communication between mini programs

青灯夜游
青灯夜游forward
2021-08-17 10:43:594078browse

This article will share with you several common methods of cross-page communication between small programs. You can refer to it if necessary.

A brief discussion on several ways of cross-page communication between mini programs

The applet is composed of pages. If there is a routing stack, it is [A,B], A->BValues ​​can naturally be passed layer by layer, but B->Apassing data requires additional auxiliary methods. Several common methods are discussed below. [Related learning recommendations: 小program development tutorial]

1. localStorage onShow

Application scenario: A->B/B-> ;A can be used

Advantages: Simple operation, easy to understand

Disadvantages: When calling storage, the setting may fail; and after setting, it is a persistent cache, which may pollute the original logic and should be deleted in time

Application examples:

// 以A->B示例

// A 页面
Page({
    onShow(){
        if(wx.getStorageSync('$datas')){
            console.log(wx.getStorageSync('$datas'))  // 11111
        }
    },
})

// B 页面
Page({
    someActions(){
        wx.setStorageSync('$datas','11111')
    },
})

2, globalData onShow

Application scenarios: A->B/B->A are all acceptable

Advantages: Simple operation, easy to understand; direct operation of globalData objects, higher execution efficiency than storage

Disadvantages: After setting, it can be accessed during the life cycle of the mini program, which may pollute the original logic. Delete

application example in time:

// 以A->B示例

// A 页面
const app = getApp();
Page({
    onShow(){
        if(app.globalData.$datas){
            console.log(app.globalData.$datas)  // 11111
        }
    },
})

// B 页面
const app = getApp();
Page({
    someActions(){
        app.globalData.$datas = '11111';
    },
})

3. EventChannel

provided by the mini program itself Application scenarios: Mainly B->A

Advantages: The mini program is provided natively and can be destroyed at any time

Disadvantages: Only limited to navigateTo, and requires a basic library version Not less than 2.7.3

Application example:

// A页面
wx.navigateTo({
  url: 'B?id=1',
  events: {
    // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
    ...
  },
  success: function(res) {
    // 通过eventChannel向被打开页面传送数据
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
  }
})


// B页面
Page({
  onLoad: function(option){
    console.log(option.query)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
    eventChannel.emit('someEvent', {data: 'test'});
    // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function(data) {
      console.log(data)
    })
  }
})

4. Custom EventBus

Application scenario: A->B/B- >A can

Advantages: Custom implementation, extensible

Disadvantages: Extend custom variables to wx, the same eventName may be repeatedly bound to listening events

EventBus: Refer to this EventBus implementation

Application example:

// app.js
const EventBus = require('./utils/eventBus.js');
App({
    onLaunch(){
        // 将eventBus初始到wx上
        wx['$uhomesBus'] = (function () {
            if (wx['$uhomesBus']) return wx['$uhomesBus'];
            return new EventBus();
        })();
    }
})

// A页面
Page({
    someActions(){
        wx.$uhomesBus.$on('$datas',(data)=>{
            console.log(data); // 11111
        })
    },
})

// B页面
Page({
    emitActions(){
        wx.$uhomesBus.$emit('$datas', '11111');
    },
})

5. Get the page stack instance getCurrentPages

application scenario : Mainly B->A

Advantages: The mini program is provided natively, and the processing logic is basically on the B page

Disadvantages: It is necessary to add corresponding rules for matching pages, and there are at least two routing stacks Page existence

Application example:

// A页面
Page({
    someActions(datas){
        console.log(datas); // 11111
    },
})


// B页面
Page({
    someActions(){
        const pages = getCurrentPages();
        if (pages.length < 2) return;
        
        // 如果页面层级较多,可用循环去匹配到A页面;
        // 此处仅做2个页面的示例
        const prevPage = pages[pages.length - 1];
        
        // 路由匹配到A
        if (prevPage.route === &#39;A&#39;) {
            prevPage.someActions(&#39;11111&#39;);
        }
    },
})

6, globalData proxy

This method has not been tested yet, but it is feasible in principle;

For the corresponding principle, please refer to the combination of data hijacking and subscription notification of Vue3;

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of A brief discussion on several ways of cross-page communication between mini programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete