微信小程序之頁面之間四種通訊方式

類似于vue中的組件傳值,可以應用于很多場景,用的最多的則是路由跳轉(zhuǎn)傳值和獲取上一頁面的數(shù)據(jù)

一. 頁面跳轉(zhuǎn)傳參:直接在url后拼接

  wx.navigateTo({
      //可以使用反引號,用${}的形式,里面可以寫入js表達式
      url: `/pages/index/index?id=${id}`,
    })

接收

  onLoad: function (options) {
    //接收參數(shù)
    console.log(options.id); //打印上一頁面?zhèn)鬟f的id值
  },

二、eventChannel:和被打開頁面進行通信

jumpChannel() {
    let that = this
    console.log('jumpChannel','111111111111111111111');
    wx.navigateTo({
      url: '../eventB/eventB',
      events:{
        someEvent:function(data) { //從其他頁面返回的參數(shù)
          console.log('jumpChannel',data)
          that.setData({
            channelTxt:data.data
          })
        }
      },
      success:function(res) {  //向下一個頁面?zhèn)鲄?        res.eventChannel.emit('channelA',{data: 'content from first page'})
      }
    })
  },

第二個頁面eventB.js

從第一個頁面過來時,onLoad里接收參數(shù)key=channelA,點擊頁面按鈕,返回上級頁面時,傳參key=someEvent

tap() {
    event.pub('home','this is new content')
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('someEvent',{data:'back from second page '})
    wx.navigateBack({
      delta: -1,
    })
  },
 
  /**
   * 生命周期函數(shù)--監(jiān)聽頁面加載
   */
  onLoad: function (options) {
    var that = this
    const eventChannel = this.getOpenerEventChannel()
    // eventChannel.emit('someEvent',{data:'back from second page '})
    eventChannel.on('channelA',function(data) {
      console.log('eventB',data)
      that.setData({
        content:data.data
      })
 
    })
  },

三、使用全局變量傳值
app.js中定義一個全局的空屬性,到當前頁面獲取全局屬性,并且賦需要傳遞的值給這個全局屬性,再到跳轉(zhuǎn)之后的頁面獲取這個全局屬性,用其進行相應的操作,之后再賦值為空

App({
  
  globalData:{
    data:'',
  }
})
const app = getApp()
Page({
  onLoad: function (options) {
    //將全局變量進行賦值
    app.globalData.data = '二級頁面'
    console.log(app.globalData.value);  //打印 二級頁面
  }
})

觸發(fā)回調(diào)后,任意頁面都可以使用,使用完之后賦值為空即可

四、利用緩存?zhèn)髦担?/h3>
wx.setStorageSync('goods', '新頁面') 
let value = wx.getStorageSync('goods')
console.log(value); //打印 新頁面

五、父子組件的通訊方式:
1、屬性綁定:

屬性綁定用于實現(xiàn)父向子傳值,而且只能傳遞普通類型的數(shù)據(jù),無法將方法傳遞給子組件

<tabDemo activeIdx="{{0}}"></tabDemo>
Component({
  properties: {
    activeIdx: {
      type: Number,
      value: 0
    }
  },
}

2、事件綁定:

事件綁定用于實現(xiàn)子向父傳值,可以傳遞任何類型的數(shù)據(jù)

使用步驟:

(1)在父組件的.js中,定義一個函數(shù),這個函數(shù)即將通過自定義事件的形式,傳遞給子組件

//和data平齊
syscCount(){
},

(2)在父組件的.wxml中,通過自定義事件的形式,將步驟一定義的函數(shù)引用傳遞給子組件

<mydemo4 count="{{count}}" bind:sysc="syscCount"></mydemo4>

(3)在子組件的.js中,通過調(diào)用this.triggerEvent('自定義事件名稱',{/參數(shù)對象/}),將數(shù)據(jù)發(fā)送到父組件

methods: {
  addCount(){
    this.setData({
      count:this.properties.count + 1
    })
    // 觸發(fā)自定義事件,將數(shù)值同步給父組件
    this.triggerEvent('sysc',{value:this.properties.count})
  }
}

(4)在父組件的.js中,通過e.detail獲取到子組件傳遞過來的數(shù)據(jù)

//和data平齊
syscCount(e){
  console.log('sysCount!!!');
  // console.log(e.detail.value);
  this.setData({
    count:e.detail.value
  })
},
  1. 獲取組件實例:

可在父組件里調(diào)用 this.selectComponent( id 或 class選擇器),獲取子組件的實例對象,從而直接訪問子組件的任意數(shù)據(jù)和方法。調(diào)用時需要傳入一個選擇器。

//.wxml
<mydemo4 count="{{count}}" bind:sysc="syscCount" class="child" id="childId"></mydemo4>
<view>-------</view>
<view>父組件中,count的值是:{{count}}</view>
<button bindtap="getChild">獲取子組件的實例對象</button>
 
//.js
getChild(){ //按鈕的 tap 處理函數(shù)
  // 切記下面參數(shù)不能傳遞標簽選擇器,只能的id或者class,否則會返回 null
  const child = this.selectComponent('.child')
  // console.log(child);
  // child.setData({
  //   count:child.properties.count + 1
  // })
  child.addCount()
}

4、behaviors

behaviors是小程序中,用于實現(xiàn)組件間代碼共享的特性,類似于 Vue.js 中的 “mixins”。

每個 behaviors 可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法。組件引用它時,它的屬性、數(shù)據(jù)和方法會被合并到組件中,每個組件可以引用多個behaviors,behavior也可以引用其它behavior。

(1)創(chuàng)建behaviors

//調(diào)用 Behavior() 方法,創(chuàng)建實例對象并使用 module.exports 把 behavior 實例對象共享出去
module.exports = Behavior({
  // 屬性節(jié)點
  properties:{},
  // 私有數(shù)據(jù)節(jié)點
  data:{
    username:'zs'
  },
  // 事件處理函數(shù)和自定義方法
  methods:{},
  // 其他節(jié)點。。。
})

(2)導入并使用 behavior

在組件中,使用 require() 方法導入需要的 behavior,掛載后即可訪問 behavior 中的數(shù)據(jù)和方法。

// 使用 require() 導入需要的自定義 behavior 模塊
const myBehavior = require('../../behaviors/my-behaviors')
 
Component({
  // 將導入的 behavior 實例對象掛載到 behavior 數(shù)組節(jié)點中,即可生效
  behaviors:[myBehavior],
})

3)behavior中所有可用的節(jié)點

可用的節(jié)點 類型 可選項是否必須 描述
properties Object Map 否 同組件的屬性
data Object 否 同組件的數(shù)據(jù)
methods Object 否 同自定義組件的方法
behaviors String Array 否 引入其它的 behavior
created Function 否 生命周期函數(shù)
attached Function 否 生命周期函數(shù)
ready Function 否 生命周期函數(shù)
moved Function 否 生命周期函數(shù)
detached Function 否 生命周期函數(shù)
(4)同名字段的覆蓋和組合規(guī)則

組件和它引用的 behavior 中可以包含同名字段,對這些處理的字段有如下三種同名處理規(guī)則:

同名的數(shù)據(jù)字段(data):

若同名的數(shù)據(jù)字段都是對象類型,會進行對象合并;
其余情況會進行數(shù)據(jù)覆蓋,覆蓋規(guī)則為: 引用者 behavior > 被引用的 behavior 、 靠后的 behavior > 靠前的 behavior。(優(yōu)先級高的覆蓋優(yōu)先級低的,最大的為優(yōu)先級最高);
同名的屬性(properties)或方法(methods):

若組件本身有這個屬性或方法,則組件的屬性或方法會覆蓋 behavior 中的同名屬性或方法;
若組件本身無這個屬性或方法,則在組件的 behaviors 字段中定義靠后的 behavior 的屬性或方法會覆蓋靠前的同名屬性或方法;
同名的生命周期函數(shù):

對于不同的生命周期函數(shù)之間,遵循組件生命周期函數(shù)的執(zhí)行順序;
對于同種生命周期函數(shù)和同字段 observers ,遵循如下規(guī)則:
behavior 優(yōu)先于組件執(zhí)行;
被引用的 behavior 優(yōu)先于 引用者 behavior 執(zhí)行;
靠前的 behavior 優(yōu)先于 靠后的 behavior 執(zhí)行;
如果同一個 behavior 被一個組件多次引用,它定義的生命周期函數(shù)和 observers 不會重復執(zhí)行。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容