Common communication methods between pages in uni app

uni-app is a framework that uses vue.js to develop all front-end applications. Developers write a set of code that can be distributed to iOS, Android, Web (response), and various small programs (WeChat / Alipay / Baidu / headline /QQ/ pin / Taobao), fast application and other platforms.

1, Communication using url parameters

Pass parameters from page A to page B

uni.navigateTo({      url: 'test/test?id=1&url=' + encodeURIComponent('https://dcloud.io')  });

Page B receives the parameters passed by page A

export default {      onLoad: function (option) { //Option is of object type, which will serialize the parameter console.log(option.id) passed on the previous page// Print out the parameters passed on the previous page. console.log(option. url); // Print out the parameters passed on the previous page.}}

2, uni.$emit() and uni.$on()

Since HBuilderX 2.0.0, it supports uni.$emit, uni.$on, uni.$once and uni.$off, which can facilitate page communication. The triggered events are at the App global level, spanning any component, page, nvue, vue, etc.

How to use it? Let's assume a scenario. When you enter the app, you are not logged in. You need to click log in on my page and enter the log in page to log in. After successful login, return to my page to display the user information after login in real time.

Listening events

First, listen for events on my page. ​​​​​​

// My page onLoad() {/ / listens to the event Uni. $on ('login ', (usnerinfo) = > {this. Usnerinfo = usnerinfo;})}, onunload() {/ / removes the listening event uni.$off('login');},

Because event listening is global, when using uni.$on, you need to use uni.$off to remove global event listening and avoid repeated listening.

Trigger event

Enter the login page and trigger the event

// Login page Uni. $emit ('login ', {avatarurl:' https://img-cdn-qiniu.dcloud.net.cn/uploads/nav_menu/10.jpg ',        token: 'user123456',        userName: 'unier',        login: true  });

After triggering an event with uni.$emit, the corresponding uni.$on will listen to the event trigger and execute the relevant logic in the callback.

More usage scenarios

The above is just a simple scenario application. During our development, we will encounter many communication scenarios between pages, such as:

  • vue and nvue, communication between nvue and vue
  • Communication between tabbar pages
  • Communication between parent pages and multi-level child pages

Basically, the above scenarios can be realized. In essence, one page informs another that I have changed. You need to deal with it.

The communication of most pages can be completed by using four events: uni.$emit, uni.$on, uni.$once and uni.$off.

Tips

  • If the page is not opened, the listening events uni.$on and uni.$once cannot be registered.
  • For one-time events, you can directly use uni.$once to listen without removing it.

Use EventBus for communication

//Register the eventBus object with Vue's prototype

Vue.prototype.$eventBus = new Vue()

//Add a click event on page A and send a message to page B

<button @click="sendMsg">Send</button>
sendMsg() {  this.$eventBus.$emit("getId", 12)}

//Register listening events on page B

created() {  this.$eventBus.$on("getId", function(id) {     this.id = id   }}

3, Communicate with global variables

Common module

Define a special module to organize and manage these global variables and introduce them in the required pages.

Note that this method only supports multiple vue pages or shared between multiple nvue pages, but not shared between vue and nvue.

Examples are as follows:
Create a common directory in the root directory of the uni app project, and then create a new helper.js in the common directory to define common methods.

const websiteUrl = 'http://uniapp.dcloud.io';  const now = Date.now || function () {      return new Date().getTime();  };  const isArray = Array.isArray || function (obj) {      return obj instanceof Array;  };  
export default {      websiteUrl,      now,      isArray  }

Next, reference the module in pages/index/index.vue.

<script>      import helper from '../../common/helper.js';  
    export default {          data() {              return {};          },          onLoad(){              console.log('now:' + helper.now());          },          methods: {          }      }  </script>

This method is convenient to maintain, but the disadvantage is that it needs to be introduced every time.

Mount Vue.prototype

Some frequently used constants or methods are directly extended to Vue.prototype, and each Vue object will "inherit".

Note that this method only supports vue pages

Examples are as follows:
Mount properties / methods in main.js

Vue.prototype.websiteUrl = 'http://uniapp.dcloud.io';  Vue.prototype.now = Date.now || function () {      return new Date().getTime();  };  Vue.prototype.isArray = Array.isArray || function (obj) {      return obj instanceof Array;  };

And then call it in pages/index/index.vue.

<script>      export default {          data() {              return {};          },          onLoad(){              console.log('now:' + this.now());          },          methods: {          }      }  </script>

In this way, you only need to define it in main.js, and you can call it directly in each page.

Tips

  • Do not duplicate property or method names in each page.
  • It is recommended to add a uniform prefix to the properties or methods mounted on Vue.prototype. For example, $url, global_ In this way, the url can be easily distinguished from the content of the current page when reading the code.

globalData

There is a globalData concept in the applet, which can declare global variables on the App. Vue had no such concept before, but uni App introduced the concept of globalData and implemented it on platforms including H5 and App.

In App.vue, you can define globalData, or use the API to read and write this value.

globalData supports vue and nvue to share data.

globalData is a relatively simple way to use global variables.

Definition: App.vue

<script>      export default {          globalData: {              text: 'text'          },          onLaunch: function() {              console.log('App Launch')          },          onShow: function() {              console.log('App Show')          },          onHide: function() {              console.log('App Hide')          }      }  </script>  
<style>      /*Public css per page */  </style>

The operation of globalData in js is as follows:

Assignment: getApp().globalData.text = 'test'

Value: console.log(getApp().globalData.text) // 'test'

If you need to bind the data of globalData to the page, you can re assign the variable in the onshow declaration cycle of the page. Since HBuilderX 2.0.3, the nvue page also supports onshow in the uni app compilation mode.

4, Vuex

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.

HBuilderX 2.2.5 + supports sharing between vue and nvue. reference resources

Here, take the synchronous update of user information after login as an example to briefly explain the usage of vuex. For more detailed content of vuex, it is recommended to go to its official website   Vuex   Learn.

For example:

Create a new store directory under the root directory of the uni app project, and create index.js under the store directory to define the status value.

const store = new Vuex.Store({      state: {          login: false,          token: '',          avatarUrl: '',          userName: ''      },      mutations: {          login(state, provider) {              console.log(state)              console.log(provider)              state.login = true;              state.token = provider.token;              state.userName = provider.userName;              state.avatarUrl = provider.avatarUrl;          },          logout(state) {              state.login = false;              state.token = '';              state.userName = '';              state.avatarUrl = '';          }      }  })

Then, you need to mount Vuex in main.js

import store from './store'  Vue.prototype.$store = store

Finally, it is used in pages/index/index.vue

 

​​​​​​​

<script>      import {          mapState,          mapMutations      } from 'vuex';  
    export default {          computed: {              ...mapState(['avatarUrl', 'login', 'userName'])          },          methods: {              ...mapMutations(['logout'])          }      }  </script>

For detailed examples, please download the attachment and run it in HBuilderX.

Example operation steps: prompt to log in when you are not logged in. After jumping to the login page, click "login" to obtain user information. After synchronizing the update status, return to the personal center to see the results of information synchronization.

Note: compared with the previous method, this method is more suitable for dealing with global situations where the value will change.

matters needing attention

*. Vue and. nvue are not specifications, so some schemes applicable in. Vue do not apply to. nvue. Mount properties on Vue and cannot be used in. nvue**

5, nvue and vue communicate with each other

step
1. Use uni.postMessage(data) on the nvue page to send data. Data can only be json data,
2. On the app.vue page, use onUniNViewMessage to listen and receive data
Code example
nvue page

<template>    <div @click="test">        <text>Click the page to send data</text>    </div></template><script>    export default {        methods: {            test(e) {                uni.postMessage({test: "data",value:"data"});            }        }    }</script>

App.vue

<script>    export default {        onUniNViewMessage:function(e){          console.log("App.vue Data received")          console.log(JSON.stringify(e.data))          },        onLaunch: function() {            console.log('App Launch');        }    }</script>

Keywords: Javascript Front-end Vue.js

Added by aubeasty on Thu, 09 Dec 2021 04:11:06 +0200