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

// Jump to the destination page and open a new pagebn.navigateTo({  url: '/pages/page/path/name'})
// Jump to the destination page and open it on the current pagebn.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

// pass in the parameter id=2&type=testbn.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 onShow() lifecycle of the target page:

Page({  onShow() {    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 Abn.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 BPage({  onShow() {    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)    })  }})