Five Ways for WeChat applets to communicate with each other, five ways for applets

Source: Internet
Author: User

Five Ways for communication between small program pages and five small program pages

PageModel is an important concept for small programs. It can be seen from app. json that small programs are composed of pages.

For example, this is a common small program: the home page is a dual-Tab framework PageA and PageB, sub-pages pageB and PageC.

Let's assume that the homepage PageA has a floating number. When we start PageC from PageA and perform some operations and return to PageA, the floating number should be refreshed. Obviously, this requires that PageA be notified when you perform operations in PageC, so that PageA can make relevant linkage changes.

Here, the major point of the notification is page communication. For communication, u3 considers that the following two conditions must be met:

  1. Activate a method call from the other party
  2. Ability to transmit data to activated Methods

This article will discuss and summarize the communication methods between pages based on the project practice and the characteristics of applets.

Communication category

By page level (or display path), it can be divided:

  1. Communication between brothers. For example, communication between multiple Tab pages, communication between PageA and PageB
  2. The parent path page communicates with the sub-path page, for example, PageA communicates with PageC.
  3. The sub-path page communicates with the parent path page, for example, PageC communicates with PageA.

When the method of activating the other party is used during communication, it can be divided:

  1. Delayed activation, that is, after I finish the operation in PageC, I will call the method after returning to PageA and activating PageA.
  2. Activate now, that is, after I finish the operation in PageC, The PageA activation method is called in PageC.

Method 1: onShow/onHide + localStorage

Use the onShow/onHide Activation Method to transmit data through localStorage. The logic is as follows:

// PageAlet isInitSelfShow = true; Page ({data: {helloMsg: 'Hello from PageA '}, onShow () {// onShow will also be triggered during Page initialization, in this case, you do not need to check the communication if (isInitSelfShow) return; let newHello = wx. getStorageSync ('_ data'); if (newHello) {this. setData ({helloMsg: newHello}); // display the wx of the previous communication data. clearStorageSync ('_ data') ;}}, onHide () {isInitSelfShow = false ;}, goC () {wx. navigateTo ({url: '/pages/c/C '});}});
// pageCPage({ doSomething() {  wx.setStorageSync('__data', 'hello from PageC'); }});

Advantages:Easy to understand

Disadvantages:If the communication data is not cleared immediately after communication is completed, problems may occur. In addition, due to dependency on localStorage, localStorage may fail to read/write, resulting in communication failure

Note:OnShow is also triggered during page initialization.

Method 2: onShow/onHide + applet globalData

Like method 1, onShow/onHide activation is used to complete data transmission by reading and writing the globalData program.

// PageAlet isInitSelfShow = true; let app = getApp (); Page ({data: {helloMsg: 'Hello from PageA '}, onShow () {if (isInitSelfShow) return; let newHello = app. $ data. helloMsg; if (newHello) {this. setData ({helloMsg: newHello}); // clears the app for the last communication data of the team. $ data. helloMsg = null ;}, onHide () {isInitSelfShow = false ;}, goC () {wx. navigateTo ({url: '/pages/c/C '});}});
// PageClet app = getApp();Page({ doSomething() {  app.$$data.helloMsg = 'hello from pageC'; }});

Advantages:Easy to implement and understand. Because it does not read or write localStorage and directly operates the memory, it is faster and more reliable than method 1.

Disadvantages:Same as method 1, pay attention to globalData pollution.

Method 3: eventBus (or PubSub)

In this way, you must first implement a PubSub and implement communication through subscription and publishing. When releasing an event, activate the method of the other party, and input parameters to execute the event subscription method.

/*/Plugins/pubsub. js * a simple PubSub */export default class PubSub {constructor () {this. pubSubCache = {$ uid: 0 };}on (type, handler) {let cache = this. pubSubCache [type] | (this. pubSubCache [type] ={}); handler. $ uid = handler. $ uid | this. pubSubCache. $ uid ++; cache [handler. $ uid] = handler;} emit (type ,... param) {let cache = this. pubSubCache [type], key, tmp; if (! Cache) return; for (key in cache) {tmp = cache [key]; cache [key]. call (this ,... param) ;}}off (type, handler) {let counter = 0, $ type, cache = this. pubSubCache [type]; if (handler = null) {if (! Cache) return true; return !! This. PubSubCache [type] & (delete this. PubSubCache [type]);} else {!! This. PubSubCache [type] & (delete this. PubSubCache [type] [handler. $ uid]) ;}for ($ type in cache) {counter ++;} return! Counter & (delete this. PubSubCache [type]) ;}}
//pageAlet app = getApp();Page({ data: {  helloMsg: 'hello from PageA' }, onLoad() {  app.pubSub.on('hello', (number) => {   this.setData({    helloMsg: 'hello times:' + number   });  }); }, goC() {  wx.navigateTo({   url: '/pages/c/c'  }); }});
//pageClet app = getApp();let counter = 0;Page({ doSomething() {  app.pubSub.emit('hello', ++counter); }, off() {  app.pubSub.off('hello'); }});

Disadvantages:Pay attention to repeated binding.

Method 4: gloabelData watcher

As mentioned above, globalData is used for communication. Nowadays, data binding is popular. Combined with the idea of redux single store, if we watch a globalData directly, we only need to modify the data value to activate the call through water to communicate. The modified data value can be used as the parameter data.

For ease of demonstration, we use the oba open source Library as the object monitoring library. If you are interested, you can implement one by yourself.

//pageAimport oba from '../../plugin/oba';let app = getApp();Page({ data: {  helloMsg: 'hello from PageA' }, onLoad() {  oba(app.$$data, (prop, newvalue, oldValue) => {   this.setData({    helloMsg: 'hello times: ' + [prop, newvalue, oldValue].join('#')   });  }); }, goC() {  wx.navigateTo({   url: '/pages/c/c'  }); }});
//pageClet app = getApp();let counter = 0;Page({ doSomething() {  app.$$data.helloTimes = ++counter; }});

Advantages:Data-driven, single data source for easy debugging

Disadvantages:The problem of repeated watch still exists. You need to avoid it.

Method 5: Use the hack method to directly call the communication page

Directly cache the page PageModel. During communication, you can directly find the PageModel of the page to be communicated, and then you can access all the attributes and methods of the PageModel on the communication page. It cannot be cool. Thanks to our friends in the Group for discovering this amazing method. Someone will certainly ask how to get all the pagemodels. Others are quite simple. Each page has an onLoad method. In this event, we can cache this (some page pagemodels) and use the page path as the key to facilitate searching. How can we obtain the page path? The answer is the page _ route _ attribute.

// Plugin/pages. js // cache pageModel, a brief implementation of export default class PM {constructor () {this. $ cache ={};} add (pageModel) {let pagePath = this. _ getPageModelPath (pageModel); this. $ cache [pagePath] = pageModel;} get (pagePath) {return this. $ cache [pagePath];} delete (pageModel) {try {delete this. $ cache [this. _ getPageModelPath (pageModel)];} catch (e) {}}_ getPageModelPath (page) {// key point return page. _ route __;}}
// pageAlet app = getApp();Page({ data: {  helloMsg: 'hello from PageA' }, onLoad() {  app.pages.add(this); }, goC() {  wx.navigateTo({   url: '/pages/c/c'  }); },  sayHello(msg) {  this.setData({   helloMsg: msg  }); }});
// PageClet app = getApp (); Page ({doSomething () {// witness the miraculous moment app. pages. get ('pages/a/'). sayHello ('Hello u3xyz.com ');}});

Advantages:It has powerful functionality and can do anything you want to do on the page. No need to bind and subscribe, so there is no duplicate

Disadvantages:The hack attribute _ route _ is used, which may cause some risks.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.