Mini Program page jump and communication

When developing small programs , you will encounter the need to jump between pages. There are many ways to jump pages between small programs, which can be roughly divided into two categories, one is the command method, and the other is controlled by js.

1. js control jump

1、wx.navigateTo

wx.navigateTo is used to retain the current page and jump to a certain page in the application, and wx.navigateBack can be used to return to the original page. For applets with not too many pages, it is usually recommended to use wx.navigateTo to jump to return to the original page to improve the loading speed. It is not recommended when there are too many pages.

// 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。
// 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈,但是 redirectTo 
wx.navigateTo({
  url: 'page/home/home?user_id=111'
})

2、wx.navigateBack

wx.navigateBack is used to close the current page and return to the previous page or multi-level pages. Developers can get the current page stack through getCurrentPages() and decide how many layers to return. The only parameter that needs to be filled in this API is delta, indicating the number of pages to be returned. If the value of delta is greater than the number of pages that can be returned, it will return to the first page where the user enters the applet. When the value of delta is not filled in, it will default to 1 (note that the default is not 0), that is, return to the previous page

// 关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。

wx.navigateTo({
  url: 'page/home/home?user_id=111'  // 页面 A
})
wx.navigateTo({
  url: 'page/detail/detail?product_id=222'  // 页面 B
})
// 跳转到页面 A
wx.navigateBack({
  delta: 2
})

3、wx.redirectTo

wx.redirectTo When there are too many pages, the reserved pages will occupy the memory allocated by WeChat to the applet, or reach the 5-layer page stack limited by WeChat. At this time, we should consider choosing wx.redirectTo. wx.redirectTo() is used to close the current page and jump to a page in the application. Such a jump can prevent the page from occupying the running memory before the jump, but the page needs to be reloaded when returning, which increases the display time of the returned page.

// 关闭当前页面,跳转到应用内的某个页面。
wx.redirectTo({
  url: 'page/home/home?user_id=111'
})

4、wx.switchTab

It is dedicated to tabBar pages. For pages that jump to the tab bar, it is best to choose wx.switchTab(), which will first close all non-tab bar pages. Secondly, you can also choose wx.reLaunch(), which can also realize the jump from non-tab bar to tab bar, or jump between tab bars, and the effect is equivalent to wx.switchTab(). If you use other jump APIs to jump to the tab bar, the jump will fail.

// 跳转到tabBar页面(在app.json中注册过的tabBar页面),同时关闭其他非tabBar页面。
wx.switchTab({
  url: 'page/index/index'
})

5、wx.reLaunch

The purpose of wx.reLaunch() and wx.redirectTo() is basically the same, except that wx.reLaunch() first closes all reserved pages in memory, and then jumps to the target page.

// 关闭所有页面,打开到应用内的某个页面。
wx.reLanch({
  url: 'page/home/home?user_id=111'
})

2. Instructional jump

// navigator 组件默认的 open-type 为 navigate 
<navigator url="/page/navigate/navigate?title=navigate" hover-class="navigator-hover">跳转到新页面</navigator>
// redirect 对应 API 中的 wx.redirect 方法
<navigator url="../../redirect/redirect/redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">在当前页打开</navigator>
// switchTab 对应 API 中的 wx.switchTab 方法
<navigator url="/page/index/index" open-type="switchTab" hover-class="other-navigator-hover">切换 Tab</navigator>
// reLanch 对应 API 中的 wx.reLanch 方法
<navigator url="../../redirect/redirect/redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">关闭所有页面,打开到应用内的某个页面</navigator>
// navigateBack 对应 API 中的 wx.navigateBack 方法
<navigator url="/page/index/index" open-type="navigateBack" hover-class="other-navigator-hover">关闭当前页面,返回上一级页面或多级页面</navigator>

The open-type attribute of navigator can have the optional values ​​'navigate', 'redirect', and 'switchTab', corresponding to the functions of wx.navigateTo, wx.redirectTo, and wx.switchTab:

open-type="navigate" is equivalent to API's wx.navigateTo 

The url of wx.navigateTo is the path of the non-tabBar page in the application that needs to be redirected

open-type="redirect" is equivalent to wx.redirectTo of the API, and the url of wx.redirectTo is the path of the non-tabBar page in the application that needs to be redirected. open-type="switchTab" is equivalent to the API 

wx.switchTab and the url of wx.switchTab needs to jump to the tabBar page and close all other non-tabBar pages.

3. Page communication

1. Use the url path to pass

1.1, passing ordinary strings

By splicing parameters after the url, use ? to separate parameters and paths, connect parameter keys and parameter values ​​with =, and separate different parameters with &; such as 'path?key=value&key2=value2'.

// A页面跳转代码
goB(){
    wx.navigateTo({
      url: '/pages/B/index?id=value',
    })
  },

// B页面接收代码
onLoad: function (options) {
    console.log('id', options.id)
}

1.2, transfer object

The above case is a string parameter, but in many cases it is necessary to pass an object. At this time, you need to first convert the object object into a JSON string through JSON.stringify(obj) for parameter passing, and then parse and use it through JSON.parse on the receiving page.

// A页面跳转代码
goB(){
   let userStr = JSON.stringify(this.data.userInfo)
   wx.navigateTo({
     url: '/pages/B/index?id='+userStr,
   })
 }

// B页面接收代码
onLoad: function (options) {
    console.log('id', JSON.parse(options.id))
  }

2. Use the globalData global variable

globalData is a fixed attribute in the applet app.js, and the stored data can be used anywhere in the whole project

// app.js
App({
  globalData:{},
})

// aaa.js
const app = getApp();
app.globalData.name='xiaowang';

// bbb.js
const app = getApp();
console.log(app.globalData.name) //xiaowang

3. Use storage data cache

Storage is the cache allocated by WeChat to each applet. The maximum value for a single parameter is 1M, and the maximum total data is 10M.

// aaa.js
Page({
    data:{
        name:'xiaowang'    
    },
})
//只支持原生类型、Date、及能够通过JSON.stringify序列化的对象
wx.setStorageSync('name',this.data.name)

// bbb.js
console.log(wx.getStorageSync(name)) //xiaowang

4, incident communication

via the event communication channel

// A页面跳转代码
goB() {
    wx.navigateTo({
      url: '/pages/B/index',
      success:(res)=>{
            // 发送一个事件
            res.eventChannel.emit('toB',{ userInfo: this.data.userInfo })
        }
    })
  }

// B页面接收代码
onLoad: function (options) {
     // 获取所有打开的EventChannel事件
     const eventChannel = this.getOpenerEventChannel();
     // 监听 index页面定义的 toB 事件
     eventChannel.on('toB', (res) => {
       console.log(res.userInfo) 
     })
   }

Create data channels directly on multiple pages of ABC

//注意this.getOpenerEventChannel() 只能在navigateTo模板页面使用,其他更多页面使用时,
//可以保存在getApp()全局实例中以备其他页面使用
// 保留AB通道事件,已备C页面给A页面发送数据
// B页面
    const eventChannel = this.getOpenerEventChannel()
    getApp().pageBEventChannel = eventChannel
//C页面 
 getApp().pageBEventChannel.emit('PageAacceptDataFromPageC', { data: 'Page C->A' });

5. Use third-party iny bus events

GitHub official website: GitHub - landluck/iny-bus: Event bus, event communication, support for major platform applets (WeChat applet, Alipay applet, etc.)

5.1. Installation

Method 1. Install via npm

# npm
npm i iny-bus -save

# yarn
yarn add iny-bus --production

Method 2. Download code

Download the iny-bus source code directly through git, and copy index.js in the dist directory to your own project

git clone https://github.com/landluck/iny-bus.git

5.2. Use

Use the built-in method


  // App、Page、Component 使用方法一致
  import bus from 'iny-bus'

  // bus.app bus.page bus.component
  const page = bus.page({
    busEvents: {
      // 简单使用
      postMessage(msg) {
        this.setData({
          msg
        })
      },
      // 一次性事件
      postMessageOnce: {
        handler (msg) {
          this.setData({
            msg
          })
        },
        once: true
      }
    },
    onLoad() {
      bus.emit('postMessage', 'hello bus')
      bus.emit('postMessageOnce', 'hello bus once')
    }
  })

  Page(page)

used in the lifecycle


  // 小程序
  import bus from 'iny-bus'

  // 添加事件监听
  // 在 onLoad 中注册, 避免在 onShow 中使用
  onLoad () {
    this.eventId = bus.on('事件名', (a, b, c, d) => {
      // 支持多参数
      console.log(a, b, c, d)

      this.setData({
        a,
        b,
        c
      }
    })
  }

  // 移除事件监听,该函数有两个参数,第二个事件id不传,会移除整个事件监听,传入ID,会移除该页面的事件监听,避免多余资源浪费, 在添加事件监听后,页面卸载(onUnload)时建议移除
  onUnload () {
    bus.remove('事件名', this.eventId)
  }
 
  // 派发事件,触发事件监听处更新视图
  // 支持多参传递
  onClick () {
    bus.emit('事件名', a, b, c)
  }
  
  // 清空所有事件监听
  onClear () {
    bus.clear()
  }

Guess you like

Origin blog.csdn.net/qq_62594984/article/details/129893137