Skip to main content

Router

Routing API#

In mini program, the routing feature comes by default and does not require additional routing configuration by the developer.

We just need to specify the pages in the config configuration of the entry file, and then we can jump to the destination page in our code through the API provided by mini program, for example

import mpService from '@binance/mp-service'
// Jump to the destination page and open a new pagempService.navigateTo({  url: '/pages/page/path/name'})
import mpService from '@binance/mp-service'
// Jump to the destination page and open it on the current pagempService.redirectTo({  url: '/pages/page/path/name'})

For a detailed API description, please refer API

Routing Passing#

We can redirect by adding a query string parameter after all jumped URLs, for example

import mpService from '@binance/mp-service'
// pass in the parameter id=2&type=testmpService.navigateTo({  url: '/pages/page/path/name?id=2&type=test'})

In this case, the incoming parameters will be available in the lifecycle method of the target page of the successful jump via getCurrentInstance().router.params, e.g. for the above jump, in the componentWillMount (or created in Vue) lifecycle of the target page:

import { getCurrentInstance } from '@binance/mp-service'import React, { Component } from 'react'
export default class C extends Component {  componentDidMount () {    console.log(getCurrentInstance().router.params) // output { id: 2, type: 'test' }  }}

EventChannel#

We can use EventChannel to communicate between opener page and opened page when we call navigateTo, for example

// Page Aimport mpService from '@binance/mp-service'
mpService.navigateTo({  url: '/pages/page/path/B',  events: {    // add listeners to get data from opened page    acceptDataFromOpenedPage: function(data) {      console.log(data)    },    someEvent: function(data) {      console.log(data)    }  }}).then((res) => {  // send data to opened page  res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'im opener page' })})
// Page Bimport { getCurrentInstance } from '@binance/mp-service'import React, { Component } from 'react'
export default class C extends Component {  componentDidMount () {    const eventChannel = getCurrentInstance().page.getOpenerEventChannel()    // send data to opener page    eventChannel.emit('acceptDataFromOpenedPage', {data: 'im opened page'});    eventChannel.emit('someEvent', {data: 'test'});    // add listener to get data from opener page    eventChannel.on('acceptDataFromOpenerPage', function(data) {      console.log(data)    })  }}