1. 程式人生 > 實用技巧 >【小程式】---- 頁面間通訊介面,跳轉頁面攜帶引數

【小程式】---- 頁面間通訊介面,跳轉頁面攜帶引數

一、功能描述:

在 2019 年 7 月 2 日的小程式基礎庫版本更新 v2.7.3 中,小程式新增了一個頁面間通訊的介面,幫助我們的小程式完成不同頁面間資料同步的功能。

二、實現方式:

假設頁面 A 開啟詳情頁面 B

1. A 向 B 傳遞資料

// A頁面

wx.navigateTo({
  url: 'search?type=1' 
  success: function(res) { 
  // 通過eventChannel向被開啟頁面傳送資料 
    res.eventChannel.emit('searchComplete', { searchName: 'cc' }) 
  }
})
// B頁面

onLoad: function(option){
  // 監聽searchComplete事件,獲取上一頁面通過eventChannel傳送到當前頁面的資料
  let eventChannel = this.getOpenerEventChannel();
  eventChannel.on('searchComplete', function(data) { 
   console.log(data)
})
}

2.B 向 A 傳遞資料

// A頁面

wx.navigateTo({
  url: 'search?type=1', 
  events: { 
     filterComplete: 
function(data) { console.log(data) } } })
// B頁面

onLoad: function(option){ 
   const eventChannel = this.getOpenerEventChannel();
   eventChannel.emit('filterComplete', {filterName: 'cc'}); 
  // wx.navigateBack(); 返回上一頁
}

三、注意要點
1.該功能從基礎庫 2.7.3 開始支援,低版本需做相容處理。
2.json配置檔案的 usingComponents 不能刪除,否則會報錯:“this.getOpenerEventChannel is not a function”。